C# Enumerations with Default Value Strings

This extension class adds an extension method to the Enum type. This created the ability for each value of an Enumeration to have a default text value associated with it by simple adding an attribute to each enum value.

public enum MyEnum
{
[DisplayValue("#FFFFFF")]
White
}

static public class EnumExtension
    {
        ///
        /// Will get the string value for a given enums value, this will
        /// only work if you assign the StringValue attribute to
        /// the items in your enum.
        ///

        ///
        ///
        public static string GetDisplayValue(this Enum value)
        {
            // Get the type
            Type type = value.GetType();

            // Get fieldinfo for this type
            FieldInfo fieldInfo = type.GetField(value.ToString());

            // Get the stringvalue attributes
            DisplayValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
                typeof(DisplayValueAttribute), false) as DisplayValueAttribute[];

            // Return the first if there was a match.
            return attribs.Length > 0 ? attribs[0].DisplayValue : null;
        }
    }

///

/// This attribute is used to represent a string value

/// for a value in an enum.

///

public class DisplayValueAttribute : Attribute

{

#region Public Properties

///

/// Holds the stringvalue for a value in an enum.

///

public string DisplayValue { get; protected set; }

#endregion

#region Constructor

///

/// Constructor used to init a StringValue Attribute

///

///

public DisplayValueAttribute(string value)

{

DisplayValue = value;

}

#endregion

}


   		   	

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s