I have an enum type like this as an example:
public Enum MyEnum {
enum1, enum2, enum3 };
I\'ll read a string from config file. What I n
What about something like:
public static class EnumUtils
{
public static Nullable Parse(string input) where T : struct
{
//since we cant do a generic type constraint
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Generic Type 'T' must be an Enum");
}
if (!string.IsNullOrEmpty(input))
{
if (Enum.GetNames(typeof(T)).Any(
e => e.Trim().ToUpperInvariant() == input.Trim().ToUpperInvariant()))
{
return (T)Enum.Parse(typeof(T), input, true);
}
}
return null;
}
}
Used as:
MyEnum? value = EnumUtils.Parse("foo");
(Note: old version used try/catch around Enum.Parse)