Generic version of Enum.Parse in C#
It is already implemented in .NET 4 ;) Take a look here.
MyEnum cal;
if (!Enum.TryParse<MyEnum>("value1", out cal))
throw new Exception("value1 is not valid member of enumeration MyEnum");
Also the discussion here contains some interesting points.
And in the desired syntax of the question:
MyEnum cal = Toolkit.Parse<MyEnum>("value1");
Note: Since C# forbids you from adding static extensions, you have to house the function elsewhere. i use a static Toolkit
class that contains all these useful bits:
/// <summary>
/// Converts the string representation of the name or numeric value of one or
// more enumerated constants to an equivalent enumerated object.
/// </summary>
/// <typeparam name="TEnum">An enumeration type.</typeparam>
/// <param name="value">A string containing the name or value to convert.</param>
/// <returns>An object of type TEnum whose value is represented by value</returns>
/// <exception cref="System.ArgumentNullException">enumType or value is null.</exception>
/// <exception cref=" System.ArgumentException"> enumType is not an System.Enum. -or-
/// value is either an empty string or only contains white space.-or-
/// value is a name, but not one of the named constants defined for the enumeration.</exception>
/// <exception cref="System.OverflowException">value is outside the range of the underlying type of enumType.</exception>
public static TEnum Parse<TEnum>(String value) where TEnum : struct
{
return (TEnum)Enum.Parse(typeof(TEnum), value);
}
Although constraining to System.Enum
isn't allowed by C#, it is allowed in .NET and C# can use types or methods with such constraints. See Jon Skeet's Unconstrained Melody library, which includes code that does exactly what you want.