Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to TryParse for Enum value?

Tags:

c#

enums

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; } 
like image 903
Manish Basantani Avatar asked Jul 04 '09 16:07

Manish Basantani


People also ask

Is enum TryParse case sensitive?

MyEnum. TryParse() has an IgnoreCase parameter, set it true. Yes I am aware that Enum. Parse has an ignorecase flag.

What is TEnum C#?

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.

What is enum variable?

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.


2 Answers

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.

like image 178
Thorarin Avatar answered Sep 20 '22 12:09

Thorarin


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

like image 24
Victor Arndt Mueller Avatar answered Sep 18 '22 12:09

Victor Arndt Mueller