I use a fair number of
enum
blocks, but I hate having matching
switch
statements to render them to a human readable string (or string arrays to do the same, particularly when my
enum
may have only six elements, with fixed values between 1 and hex 8000). So I worked this out to remove the problem and keep the descriptive text with the
enum
element definition.
This works by using reflection to access the DescriptionAttribute which can be applied to any control, and which can also be applied to any other object - including individual variables, should you so wish. (That might be overkill, but hey! It's your software!).
Declare these two static methods:
public static string GetDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
return value.ToString();
}
public static T ValueOf<T>(string description)
{
Type enumType = typeof(T);
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
if (GetDescription((Enum) Enum.Parse(enumType, name)).Equals(description, StringComparison.InvariantCultureIgnoreCase))
{
return (T) Enum.Parse(enumType, name);
}
}
throw new ArgumentException("The string is not a description or value of the specified enum.");
}
Now declare your enum with the DescriptionAttribute:
public enum MyEnum
{
[DescriptionAttribute("A Human readable string")]
AMachineReadableEnum,
[DescriptionAttribute("Another Human readable string")]
ASecondMachineReadableEnum,
}
And try it out:
private void ShowItWorking()
{
string s = "";
s = GetDescription(MyEnum.AMachineReadableEnum);
s += " : " + MyEnum.AMachineReadableEnum.ToString();
s += " : " + ValueOf<MyEnum>("a human READABLE string");
MyEnum me = ValueOf<MyEnum>("A HUMAN readable STRING");
s += " : " + ((int) ).ToString();
MessageBox.Show(s);
}