Thursday, March 3, 2011

Custom Description for Enumerator

Here I would like to show how we can create custom description with enum types. Typically enum types are a single word without a space, lets assume we have country enum types, but we also like to use the enum to show a fully qualified country name rather an abbreviated one: How is this possible? by defining Description attribute to enum type and by simply using reflector to read the description. I have listed down a code snippet to show how to define and consume.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
namespace EnumCustomDescription
{
public class MyEnum
{
///
/// Adding Custom Description attribute to enumerator type helps to define more descriptive enum values rather than a single word or abbriviated value
/// use reflector class to retun the description instead of the actual enum value.
///

public enum enumCountry
{
[Description("United State of America")]
USA,
[Description("Australia")]
AUS,
[Description("India")]
IND,
[Description("South Africa")]
SA,
[Description("United Arab Emites")]
UAE,
[Description("United Kingdon")]
UK
}
}

public class GetDescription
{
///
/// GetEnumeratorDescription method will return the value defined in the Enum description, this uses the reflector
/// to read the description from the enum class
///

/// enumerator
/// description of the custom attribute
public static string GetEnumeratorDescription(Enum value)
{
FieldInfo _fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] _attribute = (DescriptionAttribute[])_fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); ;
if (_attribute.Length > 0) { return _attribute[0].Description.ToString(); }
return value.ToString();
}

}
}