Introduction
I found this article a few months back on CodeProject: stringenum.aspx. It is an impressive, nice way to get enums to carry string values using attributes. After using it, I found myself with a strange need to go the other way round; i.e., given the string value, get the enum value that string is associated with.
Background
I suggest reading the article from the link above first. That article will get you to 90% of the path to "getting strings associated with enums". I am extending the functionality here to go the other way round.
Using the code
public class StringEnum
{
private Type _enumType;
public StringEnum(Type enumType)
{
if (!enumType.IsEnum)
throw new ArgumentException(String.Format(
"Supplied type must be an Enum. Type was {0}",
enumType.ToString()));
_enumType = enumType;
}
public static string GetStringValue(Enum value)
{
Type type = value.GetType();
FieldInfo fi = type.GetField(value.ToString());
StringValueAttribute[] attrs = fi.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
return (attrs.Length > 0) ? attrs[0].Value : null;
}
}
public class StringValueAttribute : Attribute
{
private string _value;
public StringValueAttribute(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
Additional functionality to get enum given string
<param name="value"></param>
public static T GetEnumForGivenString<T>(string value, int NthOccurence)
{
if (!typeof(T).IsEnum)
throw new ArgumentException(String.Format(
"Supplied type must be an Enum. Type was {0}",
typeof(T).ToString()));
T result = default(T);
int foundAtIndex = 0;
foreach (string str in Enum.GetNames(typeof(T)))
{
if (GetStringValue((Enum) Enum.Parse(typeof(T), str, true)) == value)
{
foundAtIndex++;
if(foundAtIndex == NthOccurence)
{
result = (T)Enum.Parse(typeof(T), str, true);
break;
}
}
}
return result;
}
Download the code from the referenced article and add the method given above.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.