I want to write a function which can validate a given value (passed as a string) against possible values of an enum. In the case of a match, it should return th
Enum.IsDefined will get things done. It may not be as efficient as a TryParse would probably be, but it will work without exception handling.
public static TEnum ToEnum(this string strEnumValue, TEnum defaultValue)
{
if (!Enum.IsDefined(typeof(TEnum), strEnumValue))
return defaultValue;
return (TEnum)Enum.Parse(typeof(TEnum), strEnumValue);
}
Worth noting: a TryParse method was added in .NET 4.0.