Thursday, December 22, 2005

Attributes in .NET

Attributes were definitely a bit of a blank for me initially when it came to .NET. Why would you want to have metadata within your code? What would be the point of that? It turns out that it's not that silly, especially when we come to thinking about code in terms of reflection and runtime discovery.

Note: Java has the same abilities as .NET in this area though not as highly documented. http://www-128.ibm.com/developerworks/java/library/j-dyn0429/ explains how java byte code has attributes and that each function is simply an attribute and that custom attributes may exist. Though it appears at this time there doesn't appear to be any real way to utilise this information.

On metadata attributes in .NET it's possible to use these attributes to dynamically find items in classes at runtime. This is of course especially useful if you'd like to dynamically discover load classes at runtime. Think plugins...

First of all create a custom attribute. This is simply done deriving a class from the System.Attribute class. You can use the Attribute AttributeUsage to say that it's only valid for classes and interfaces.
Write a custom interface that uses your custom attribute for the interface declaration.
Implement your interface. It is now possible with reflection to find all instances of classes that implement that interface using reflection. Simply load the current assembly (Assembly.ExecutingAssembly) and get all the types. For each type attempt to get all instances of our custom attribute. If the attribute exists then we know that the class implements our custom interface. (Also check to make sure that the class isn't abstract or an interface that we you can actually create an instance of the class).

And now you have seen how reflection can be used to find and dynamically instantiate classes. This method is used (though slightly differently), to find webservice methods. You may also see http://www.xml-rpc.net/ this uses the same sort of reflection to know what methods to marshall on a website. So there you have it. Attributes and reflection.