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; }
MyEnum. TryParse() has an IgnoreCase parameter, set it true. Yes I am aware that Enum. Parse has an ignorecase flag.
TEnum is the Generic type of enumeration. You can pass any of your enumeration to that method. The second method is a non-generic one, where you would use a typeof keyword to identify the enums and return the enum names as a string collection.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With