Home > C# > String type to ENum (Generic)

String type to ENum (Generic)

///

/// Allows the discovery of an enumeration value based on the EnumTextValueAttribute
///

/// The type of the enum to get the value for.
/// The text of the EnumTextValueAttribute.
/// boxed representation of the enum value

public static T GetEnumValue(string text)
{
Type enumType = typeof(T);

MemberInfo[] members = enumType.GetMembers();
foreach (MemberInfo mi in members)
{
object[] attrs = mi.GetCustomAttributes(typeof(EnumTextValueAttribute), false);
if (attrs.Length == 1)
{
if (((EnumTextValueAttribute)attrs[0]).Text == text)
return (T) Enum.Parse(enumType, mi.Name);
}
}
throw new ArgumentOutOfRangeException(“text”, text, “The text passed does not correspond to an attributed enum value”);
}

Advertisements
Categories: C#
  1. No comments yet.
  1. No trackbacks yet.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: