Often, we use enum
s for some selection process (switch
statements, etc.), but when we display them to the UI, we need it formatted differently (not camel hump or dash separated).
To start, attributes can be used to store the description, and should be stored in the DescriptionAttribute
:
public enum EmployeeType
{
[DescriptionAttribute("The Big Boss Man")]
Boss,
[DescriptionAttribute("Boss's lacky")]
AdministrativeAssistant,
Janitor,
[DescriptionAttribute("Everyone Else")]
StandardEmployee
}
Here, we have defined a simple enum
called EmployeeType
and added a description attribute to the ones we want to be displayed differently.
Now the interesting part. In case you are unfamiliar with Extensions, here is a link to the MSDN[^].
public static string DisplayString(this Enum value)
{
FieldInfo info = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])info.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length == 1)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
This extension to Enum
can then be used like this:
EmployeeType emp = EmplyeeType.Boss;
...
string display = emp.DisplayString();
string janDisplay = EmployeeType.Janitor.DisplayString();
In addition, if you have the description, you can easily extend the string
as well to get back to the actual enum
value.
public static object EnumValueOf<t>(this string descriptionOrValue)
{
Array tValues = Enum.GetValues(typeof(T));
foreach (Enum val in tValues)
{
if (val.DisplayString().Equals(descriptionOrValue) || val.ToString().Equals(descriptionOrValue))
{
return val;
}
}
throw new ArgumentException(string.Format("The string value is not of type {0}.", typeof(T).ToString()));
}</t>
Usage:
string display = "The Big Boss Man";
EmployeeType emp = (EmployeeType)display.EnumValueType<employeetype();>