Extension Methods with Enum Description
Since Enum names in .NET do not support certain characters like spaces, often developers will use the DescriptionAttribute to add detailed text to an Enum.
[Flags]
internal enum SuperHero
{
[Description("Clark Kent")]
Superman = 1,
[Description("Peter Parker")]
SpiderMan = 2,
[Description("Bruce Banner")]
Hulk = 4,
[Description("Tony Stark")]
IronMan = 8,
}
You can pull the description from the enum with code like this. (Keep in mind that you can make this MUCH faster using DynamicMethods and caching, but that is another article…)
private const char ENUM_SEPERATOR_CHARACTER = ',';
public static string GetDescription(Enum value)
{
// Check for Enum that is marked with FlagAttribute
var entries = value.ToString().Split(ENUM_SEPERATOR_CHARACTER);
var description = new string[entries.Length];
for (var i = 0; i < entries.Length; i++)
{
var fieldInfo = value.GetType().GetField(entries[i].Trim());
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
description[i] = (attributes.Length > 0) ? attributes[0].Description : entries[i].Trim();
}
return String.Join(", ", description);
}
Well, now with .NET 3.5 and Extension methods it only makes sense to make this a little bit easier.
public static string Description(this Enum value)
{
return GetDescription(value);
}
And now you can do the following:
var secretIdentity = SuperHero.Superman.Description();
var superHeroes = SuperHero.Superman | SuperHero.SpiderMan;
var secretIdentities = superHeroes.Description();
Note that the code handles Enum marked with the FlagAttribute as well. The output of the whole flag thing is not ideal but at least it does not break when handling those Enums.