C Sharp

Introducing Attributes

What attributes allow you to do is nothing short of ground breaking. They provide you a generic means of associating information (as annotations) with your defined C# types. You can use attributes to define design-time information (such as documentation information), run-time information (such as the name of a database column for a field), or even run-time behavioral characteristics (such as whether a given member is "transactionable"-that is, capable of participating in a transaction).

The possibilities are endless, which is rather the point. Because you can create an attribute based on any information you like, a standard mechanism exists for defining the attributes themselves and for querying the member or type at run time as to its attached attributes.

An example will better illustrate how to use this powerful feature. Let's say you have an application that stores some of its information in the Windows Registry. One design issue would be deciding where to store the Registry key information. In most development environments, this information is typically stored in a resource file or in constants or it's even hard-coded in the calls to the Registry APIs. However, once again, what we have is a situation in which an integral part of a class is being stored apart from the rest of the class's definition.

Using attributes, we could "attach" this information to the class members such that we have a completely self-describing component. Here's an example of how that would look, assuming that we had already defined the RegistryKey attribute elsewhere: -

class MyClass
{
    [RegistryKey(HKEY_CURRENT_USER, "foo")]
    public int Foo;
}

To attach a defined attribute to a C# type or member, you simply specify the attribute data in brackets before the target type or member. Here we attached an attribute named RegistryKey to the MyClass.Foo field. At run time-which you'll see shortly-all we'll have to do is query the field as to its Registry key and then use that value to save the date into the Registry.

by BrainBellupdated
Advertisement: