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.

Print | posted @ Monday, March 31, 2008 7:19 AM

Comments on this entry:

Gravatar # re: Use the DescriptionAttribute with an Enum to display status messages.
by Laurent at 4/3/2008 1:16 AM

In my opinion, the biggest issue with Enums is localization. The solution offered here doesn't help though, does it? How do you display localized messages depending on the Culture?
Gravatar # re: Use the DescriptionAttribute with an Enum to display status messages.
by Paul at 4/3/2008 4:45 AM

Laurent: you could create a new attribute type like in the "cache the values" link, and do localization that way.

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 3 and 6 and type the answer here: