C# Error CS0592 – Attribute ‘{0}’ is not valid on this declaration type. It is only valid on ‘{1}’ declarations.

C# Error

CS0592 – Attribute ‘{0}’ is not valid on this declaration type. It is only valid on ‘{1}’ declarations.

Reason for the Error & Solution

Attribute ‘attribute’ is not valid on this declaration type. It is valid on ‘type’ declarations only.

When you define an attribute, you define what constructs it can be applied to by specifying an AttributeTargets value. In the following example, the MyAttribute attribute can be applied to interfaces only, because the AttributeUsage attribute specifies AttributeTargets.Interface. The error is generated because the attribute is applied to a class (class A).

Example

The following sample generates CS0592:

// CS0592.cs  
using System;  
  
[AttributeUsage(AttributeTargets.Interface)]  
public class MyAttribute : Attribute
{  
}  
  
[MyAttribute]  
// Generates CS0592 because MyAttribute is not valid for a class.
public class A
{  
    public static void Main()  
    {  
    }  
}  

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...