Skip to content

Instantly share code, notes, and snippets.

@JoanComasFdz
Created December 28, 2011 09:14
Show Gist options
  • Save JoanComasFdz/1527223 to your computer and use it in GitHub Desktop.
Save JoanComasFdz/1527223 to your computer and use it in GitHub Desktop.
A class that uses generics to parse and get a value from an enumerator member with a StringValueAttribute.
/// <summary>
/// Provides the tools needed to get in a easy, fast way
/// the string value of an enumerator member assigned
/// with <see cref="StringValueAttribute"/>.
/// </summary>
/// <typeparam name="E">The type of the enumerator.</typeparam>
public static class StringEnum<E>
{
/// <summary>
/// Gets the enumerator member's string value.
/// </summary>
/// <param name="e">The enumerator member to get its string value.</param>
/// <returns>The argument's string value..</returns>
public static string Value(E e)
{
StringValueAttribute[] attrs = typeof(E).GetField(e.ToString()).GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
if (attrs != null && attrs.Length > 0)
return attrs[0].Value;
else
return Enum.GetName(e.GetType(), e);
}
/// <summary>
/// Returns the enumerator member that matches a given
/// string value.
/// </summary>
/// <param name="value">The string value to get its enumerator member.</param>
/// <returns>The matching enumerator member.</returns>
public static E Parse(string value)
{
return (E)Enum.Parse(typeof(E), value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment