Enumeration GetStringValue

29 Mar

First create an attribute to use on the enumeration’s values.

/// <summary>
/// This attribute is used to represent a string value for a value in an enum.
/// </summary>
/// <threadsafety>This class is mutable and not threadsafe.</threadsafety>
// Credit to:
public class StringValueAttribute : Attribute
/// <summary>
/// Holds the string value for a value in an enum.
/// </summary>
/// <value>the string value</value>
public string StringValue { get; protected set; }

/// <summary>
/// Constructor used to init a StringValue Attribute.
/// </summary>
/// <param name="value">the string value</param>
public StringValueAttribute(string value)
this.StringValue = value;

Next create an extension method to easily get the string value from the enumeration. Note: This code was downloaded from somewhere but I cannot find where I got it.

/// <summary>
/// This entensions class adds the GetStringValue method for enum to retrieve its string representation.
/// </summary>
/// <threadsafety>This class is stateless and thread safe.</threadsafety>
public static class Extensions
/// <summary>
/// This 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.
/// </summary>
/// <param name="value">the enum</param>
/// <returns>the string value</returns>
public static string GetStringValue(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
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];

// return the first if there was a match
return attribs.Length > 0 ? attribs[0].StringValue : null;
Leave a comment

Posted by on March 29, 2011 in .Net, C#, Extension


Leave a Reply

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

You are commenting using your 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

%d bloggers like this: