This topic has not yet been rated - Rate this topic

Compiler Error CS0592

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.Iterface. The error is generated because the attribute is applied to a class (class A).

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()
    {
    }
}
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Do not try to use Chrome to add a comment here...
...it messes up your post.
properties and attributes

Note that attributes can also be added directly on get and set:

public int Foo
{
   [MyAttribute(...)]
   get
   {
       return GetFoo();
   }
   [MyAttribute(...)]
   set
   {
       SetFoo(value);
   }
}