I was somewhat surprised to discover that there's no TryParse method for the Enum class in the .NET Framework 2.0. (It's also odd that the docs/compiler keep referring to Enum as a class—and yet the apprpriate where
constraint to apply is struct
.) So here's a pair of generic methods to support TryParse for Enums:
public static class EnumUtility { public static bool TryParse<T>(string value, out T result) where T : struct // error CS0702: Constraint cannot be special class 'System.Enum' { return TryParse<T>(value, out result, false); } public static bool TryParse<T>(string value, out T result, bool ignoreCase) where T : struct // error CS0702: Constraint cannot be special class 'System.Enum' { result = default(T); try { result = (T)Enum.Parse(typeof(T), value, ignoreCase); return true; } catch { } return false; } }
6 comments:
I'm continually shocked that Enum.Parse isn't a generic method.
result = (T)Enum.Parse(typeof(T), value, ignoreCase);
could turn into:
result = Enum.Parse<T>(value, ignoreCase);
You may want to make use of Enum.IsDefined instead of using a try/catch...
The trouble is that Enum.IsDefined is case sensitive.
Andrew, that is very helpful! Thank you!! I have done all variety of things to make sure I have a good value, try/catch being the worse... (too slow)
sorry it didn't work out for you Jacob, I too would prefer it worked "caseless"
Post a Comment