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 the enum instance; otherwise, it should return a default value.
The function may not internally use try
/catch
, which excludes using Enum.Parse
, which throws an exception when given an invalid argument.
I'd like to use something along the lines of a TryParse
function to implement this:
public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue)
{
object enumValue;
if (!TryParse (typeof (TEnum), strEnumValue, out enumValue))
{
return defaultValue;
}
return (TEnum) enumValue;
}
I have an optimised implementation you could use in UnconstrainedMelody. Effectively it's just caching the list of names, but it's doing so in a nice, strongly typed, generically constrained way :)
As others already said, if you don't use Try&Catch, you need to use IsDefined or GetNames... Here are some samples...they basically are all the same, the first one handling nullable enums. I prefer the 2nd one as it's an extension on strings, not enums...but you can mix them as you want!