Sunday, October 23, 2005

The role of attribute classes in .NET

.NET relies on metadata for a great extent for dependency information, security, component contracts etc. etc. Metadata is stored in the metadata tables of the assembly in machine readable format. The specifications of this format could be found in the CIL (Common Intermediate Language) specifications. CIL uses 32bit metadata tokens containing the table and the index to access these metadata.

Usually developers require passing additional information together with the code describing the code’s requirements, their intended purpose etc.. This information may be needed by the consumers of those assemblies or the .NET framework itself. Also this information is not relevant to the product domain. Rather it’s relevant to the code itself; meaning that what ever the metadata it uses, it shouldn’t affect the structure of the application.

A common example for this is Aspect Oriented Programming or AOP, where certain system wide aspects are addressed outside of object oriented designs.

.NET approach to address this requirement is Attribute classes. Attribute classes are also strongly typed and part of the framework. In fact CLR also uses Attributes for its functionality are sometimes referred to as pseudo custom attributes. Custom Attributes are the ones that developers write to request the compiler to generate metadata on a certain element.

One common example for a pseudo custom attributes is the ‘Serializable’ attribute.

[Serializable]
public class MyClass
{
//Implementation
}

No comments:

Post a Comment