Decorating an enum with the Description attribute for later use in C# with .NET
I had the need today to set a string value based on the value of an enum. Rather than creating the following code:
Edit: I added a generic method that works on all enums
string myString = null;
switch(myEnum)
{
case myEnum.Value1:
myString = "value 1";
break;
case myEnum.Value2:
myString = "value 2";
break;
case myEnum.Value3:
myString = "value 3";
break;
}
I wanted to do something simpler. So, I decided to add the System.ComponentModel.Description
attribute to my enum
, like so:
using System.ComponentModel;
public enum MyEnum
{
[Description("value 1")]
Value1,
[Description("value 2")]
Value2,
Value3
}
Then, to make it easy to use, I added an extension method to all enums:
public static class Extensions
{
public static string GetDescription(this Enum e)
{
var attribute =
e.GetType()
.GetTypeInfo()
.GetMember(e.ToString())
.FirstOrDefault(member => member.MemberType == MemberTypes.Field)
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.SingleOrDefault()
as DescriptionAttribute;
return attribute?.Description ?? e.ToString();
}
}
This will allow you to easily get the description of the current enum value. Here is how you would do that:
var testEnum = MyEnum.Value2;
var description = testEnum.GetDescription(); // Description will be "value 2".
testEnum = MyEnum.Value3;
var description2 = testEnum.GetDescription(); // Description will be "Value3".
Note that Value3 returns the name of the enum, rather than a description. That is because there is no description attribute on that enum value.
As you can see, it’s pretty easy to decorate your enum values with string descriptions. This allows you to have a central location to set the value.
I can even see a custom description attribute class that retrieves the description from a database. The use cases are there.
Another, more common use case for this method is to localize the values returned by using resource files representing the languages you want to display. You could have one for en-US, en-GB, es-ES, es-MX, etc, using the description Name as the key to the resource file.
I found a similar question on StackOverflow and provided an answer.