I\'m trying to build generic function that get from user string and try to parse it to Enum valuse like this:
private Enum getEnumStringEnumType(Type i_EnumT
Long ago in Visual Studio 2005 era, I made my own method for TryParse on Enum. I only recently discovered the 2008 implementation and I'm not happy with it's restrictiveness, especially considering that it's a TRY PARSE method; meaning that a programmer is testing an input!
Generally, I prefer to use methods which trust the programmer to know what he's doing :)
My implementation is as follows:
public static bool EnumTryParse(string input, out T theEnum)
{
foreach (string en in Enum.GetNames(typeof(T)))
{
if (en.Equals(input, StringComparison.CurrentCultureIgnoreCase))
{
theEnum = (T)Enum.Parse(typeof(T), input, true);
return true;
}
}
theEnum = default(T);
return false;
}
The lack of a where T:struct puts the trust in the developer's hands, but it allows you to compile with unknown, generic enums.
As an alternative, you can create a method looping on Enum.GetValues if you want to do an integer comparison when converting to your specified enum.
Hope this helps.