Monday, December 31, 2007

Attaching strings to enums

I Found this little cool way to attach strings to enums. Using .NET 3.5 you can do something cool and simple like this


public static class EnumExtension
{
public static string GetDescription(this Enum enumObj)
{
FieldInfo fieldInfo =
enumObj.GetType().GetField(enumObj.ToString());
object[] attribArray = fieldInfo.GetCustomAttributes(false);
if (attribArray.Length == 0)
return String.Empty;
else
{
DescriptionAttribute attrib =
attribArray[0] as DescriptionAttribute;
return attrib.Description;
}
}
}

class Program
{
public enum EmployeeType
{
[Description("Regular Employee")]
RegularEmploye,
[Description("Store Manager")]
StoreManager,
[Description("Chain Store Manager")]
ChainStoreManager,
[Description("Department Manager")]
DepartmentManager,
[Description("On Floor Supervisor")]
Supervisor
}

static void Main(string[] args)
{
string str = EmployeeType.ChainStoreManager.GetDescription();
}
}


Basically I have added an extension to the enum class to extract the value of the Description Attribute. Now, every Enum class will have a GetDescription method attached to it. This is a nice and clean way to string values out of your enums....







only supported in VS2008 using .NET 3.5

2 comments:

Paul said...

Nice, but too slow if used frequently. Reflection crawls..

Anonymous said...

The Enum class has some nice methods like: Enum.GetName or Enum.GetNames. The Enum class can even parse a string into an enum.