Display enumeration value in a user interface
Normally I wouldn’t post anything (as simple) as this but since I’ve got this question numerous times I decided to post it here anyway. Let’s say you require mapping an enumeration to both the database and a user interface representation. Although I would normally recommend a Mapper pattern to set up communication between two independent objects, I now choose to use an attribute based solution. In the code listing below the ‘Description’ attribute maps against the user interface representation and the ‘Code’ attribute maps against string based values stored in the database (a legacy database).
I borrowed the idea from this blog.
[TestFixture]
public class EnumTests
{
[Test]
public void GetDescription()
{
string description = EnumConvert.GetDescription(TrafficLight.Green);
Assert.AreEqual("Procede", description);
}
[Test]
public void GetCode()
{
string code = EnumConvert.GetCode(TrafficLight.Green);
Assert.AreEqual("G", code);
}
[Test]
public void EnumValueForCode()
{
TrafficLight t = (TrafficLight) EnumConvert.GetValue(typeof (TrafficLight), "G");
Assert.AreEqual(TrafficLight.Green, t);
}
#region Helpers
private enum TrafficLight : byte
{
[Description("Procede"), Code("G")]
Green = 0,
[Description("Caution"), Code("R")]
Red = 1
}
#endregion
}
public class CodeAttribute : Attribute
{
private string code;
public CodeAttribute(string text)
{
this.code = text;
}
public string Code
{
get { return code; }
}
}
public class EnumConvert
{
public static string GetDescription(Enum enumeration)
{
Type type = enumeration.GetType();
MemberInfo[] memInfo = type.GetMember(enumeration.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attributes = memInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
return ((DescriptionAttribute) attributes[0]).Description;
}
return enumeration.ToString();
}
public static string GetCode(Enum enumeration)
{
Type type = enumeration.GetType();
MemberInfo[] memInfo = type.GetMember(enumeration.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attributes = memInfo[0].GetCustomAttributes(typeof (CodeAttribute), false);
if (attributes != null && attributes.Length > 0)
return ((CodeAttribute) attributes[0]).Code;
}
return enumeration.ToString();
}
public static object GetValue(Type type, string code)
{
string[] names = Enum.GetNames(type);
foreach (string name in names)
{
object o = Enum.Parse(type, name);
if (GetCode((Enum) o) == code)
return o;
}
return null;
}
}