Use the DescriptionAttribute with an Enum to display status messages.
I've been working on various forms of displaying status messages from enums, and here's the latest preferred iteration of how to do this. Regurgitated and tweaked from WayneHartman.com.
public enum XmlValidationResult
{
[Description("Success.")]
Success,
[Description("Could not load file.")]
FileLoadError,
[Description("Could not load schema.")]
SchemaLoadError,
[Description("Form XML did not pass schema validation.")]
SchemaError
}
private string GetEnumDescription(Enum value)
{
// Get the Description attribute value for the 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;
}
else
{
return value.ToString();
}
}
It's possible to do something even cooler like cache the values or add a ToDescription() method (in C#3.0), but I just wanted an simple, repeatable way to do this.
Comments
Anonymous
June 04, 2014
Thanks. I added this to a class I was building to Convert an ENUM to an ItemsSource so that when I add DescriptionAttributes to an Enum I can show a "pretty" choice in dropdowns etc.Anonymous
June 09, 2015
Can i read Enum description from a xml file? Can XMLEnum be used for this purpose?