C# – How to create a custom attribute in C#

cc#-4.0custom-attributes

I have tried lots of times but still I am not able to understand the usage of custom attributes (I have already gone through lots of links).

Can anyone please explain to me a very basic example of a custom attribute with code?

Best Answer

You start by writing a class that derives from Attribute:

public class MyCustomAttribute: Attribute
{
    public string SomeProperty { get; set; }
}

Then you could decorate anything (class, method, property, ...) with this attribute:

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

and finally you would use reflection to fetch it:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
    var myAttribute = customAttributes[0];
    string value = myAttribute.SomeProperty;
    // TODO: Do something with the value
}

You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

Important things to know about attributes:

  • Attributes are metadata.
  • They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
  • The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
  • The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.