Posted by: Cirilo Meggiolaro | 10/15/2008

Tip of the day #1 – Using description with enumerators

If you are used to have enumerators in your application to describe numbers be aware that you can use a string to describe each item.

It’s not very common to use this kind of approach but here is how you can implement:


You’ll use the System.ComponentModel namespace to allow an attribute to be added to the enumerator item and the System.Reflection that will help us to get the description.

Code 1 – Namespaces


The enumerator looks like a regular enumerator except by the fact that now we have added a description attribute for each item.

Code 2 – Enumerator

Retrieving the Description

To retrieve the description we need to use the FieldInfo object that allows us to access the metadata and retrieve attributes of a field. Using the GetCustomAttributes method we can retrieve an array of attributes. Once you have the attributes, it’s just to get the description, as you can see on the next code sample:

Code 3 – Description method

Enjoy it!

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: