Posted by: Cirilo Meggiolaro | 03/3/2009

Tip of the day #140 – Reading custom attributes in runtime

Tip #139 described how to create custom attributes that you may use for your code elements such as classes, methods, enumerators and so on.

Let’s check today how to read the custom attribute in runtime using reflection. Let’s assume we have a class named OrderCollection that applies an attribute called Documentation similar to the following code:

[Documentation(“This class stores weak references of order objects.”, Scope=“This class must be used by the billing system only.”)]
public class OrderCollection { }

How to…

Here is a list of the main steps you need to follow to retrieve custom attributes information:

  • The first step you need to perform is to get a list of custom attributes from the type you expect. On our example the type if OrderCollection;
  • Loop through the array of attributes and check the attribute type;
  • Cast the attribute to the correct type and get the information you expect.

The code must be similar to the following:

Attribute[] attributes = System.Attribute.GetCustomAttributes(typeof(OrderCollection));

foreach (Attribute attr in attributes)
    if (attr is DocumentationAttribute)
        DocumentationAttribute doc = (DocumentationAttribute)attr;
        Console.WriteLine(“Description: {0} – Scope: {1}.”, doc.Description, doc.Scope);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: