RSS

Monthly Archives: March 2011

Enumeration GetStringValue

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: http://www.codeproject.com/KB/cs/stringenum.aspx
[AttributeUsage(AttributeTargets.Field)]
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

 

Why am am I blogging?

To be honest it is for selfish reasons. I have found over the years that I will read and search for code that I find interesting and then later, perhaps on another code project, I cannot find that interesting or cool post.

 
Leave a comment

Posted by on March 29, 2011 in Uncategorized