Adding custom attribute to a class

by Miro 7. August 2008 04:41

(the following example uses .NET 3.5)

1. Create a class based on the Attribute class

//define this attribue as applicable only to classes
[AttributeUsage(AttributeTargets.Class)]
public class ExtraDataAttribute : Attribute
{
         
public ExtraDataAttribute(string data)
          {
             Data = data;
          }

          public string Data { get; set; }
}

2. Decorate your class with the attribute

[ExtraData("My Data String")]
public class
MyClass
{
...
}

3. Return the attribute value at the runtime
MyClass x = new MyClass();
...

ExtraDataAttribute[] attrs = (ExtraDataAttribute[])x.GetType().GetCustomAttributes(typeof(ExtraDataAttribute), true);
//and, if we decorated the class with only one attribute of this type
string myData = attrs[0].Data;
 

Tags:

.NET

Powered by BlogEngine.NET
Contents copyright 2008 Mirocle Pty. Ltd. All Rights Reserved.