Search this blog

Sunday, April 13, 2008

Attributes

What are attributes?

There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.

[serializable] public class CTest {}

The other type of attribute is a context attribute. Context attributes use a similar syntax to metadata attributes but they are fundamentally different. Context attributes provide an interception mechanism whereby instance activation and method calls can be pre- and/or post-processed. If you have encountered Keith Brown's universal delegator you'll be familiar with this idea.

7.2 Can I create my own metadata attributes?

Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:

[AttributeUsage(AttributeTargets.Class)]

public class InspiredByAttribute : System.Attribute
{
public string InspiredBy;

public InspiredByAttribute( string inspiredBy )
{
InspiredBy = inspiredBy;
}
}

[InspiredBy("Andy Mc's brilliant .NET FAQ")]

class CTest
{
}

class CApp
{

public static void Main()
{
object[] atts = typeof(CTest).GetCustomAttributes(true);
foreach( object att in atts )

if( att is InspiredByAttribute )
Console.WriteLine( "Class CTest was inspired by{0}", ((InspiredByAttribute) att).InspiredBy );
}
}

No comments:

Post a Comment