public static T Parse<T>(string text)
{
if (!typeof(T).IsEnum)
throw new ArgumentException(typeof(T) + " is not an Enum");
try
{
return (T)Enum.Parse(typeof(T), text, true);
}
catch (Exception)
{
return default(T);
}
}
Not much to show here. I was tired of having to manage all the casting when using the Enum.Parse function. Unfortunately, I was unable to use this check
where T : System.Enum
which would have given a compilation error if you tried to use it to convert a string to an object that wasn't an Enum. Unfortunately, you can't use that as a Type parameter constraint.