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<TEnum>(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.
There's currently no out of the box Enum.TryParse. This has been requested on Connect (Still no Enum.TryParse) and got a response indicating possible inclusion in the next framework after .NET 3.5. You'll have to implement the suggested workarounds for now.
There is not a TryParse because the Enum's type is not known until runtime. A TryParse that follows the same methodology as say the Date.TryParse method would throw an implicit conversion error on the ByRef parameter.
I suggest doing something like this:
//1 line call to get value
MyEnums enumValue = (Sections)EnumValue(typeof(Sections), myEnumTextValue, MyEnums.SomeEnumDefault);
//Put this somewhere where you can reuse
public static object EnumValue(System.Type enumType, string value, object NotDefinedReplacement)
{
if (Enum.IsDefined(enumType, value)) {
return Enum.Parse(enumType, value);
} else {
return Enum.Parse(enumType, NotDefinedReplacement);
}
}
As others have said, you have to implement your own TryParse
. Simon Mourier is providing a full implementation which takes care of everything.
If you are using bitfield enums (i.e. flags), you also have to handle a string like "MyEnum.Val1|MyEnum.Val2"
which is a combination of two enum values. If you just call Enum.IsDefined
with this string, it will return false, even though Enum.Parse
handles it correctly.
Update
As mentioned by Lisa and Christian in the comments, Enum.TryParse
is now available for C# in .NET4 and up.
MSDN Docs
enum EnumStatus
{
NAO_INFORMADO = 0,
ENCONTRADO = 1,
BLOQUEADA_PELO_ENTREGADOR = 2,
DISPOSITIVO_DESABILITADO = 3,
ERRO_INTERNO = 4,
AGARDANDO = 5
}
...
if (Enum.TryParse<EnumStatus>(item.status, out status)) {
}
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!