Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tryparse and IsDefined for Enum in C#

Tags:

c#

.net

enums

All, I have to do is:

Find out whether a string is a valid Enum element and if so, return status.

something like, If I have an enum say Enum_Test which in turn consists of red, blue , green as its value.

Now, if blue is the element to be verified, I use something like

Enum_Test evalue;
if(Enum.TryParse(string_Verify, true, out evalue))  
{
        return true;
}

Or otherwise I have an another option,

if( Enum.IsDefined(typeof(Enum_Test), string_Verify))
{
        return true;
}

What is the advantages and pit falls in the above methods ?

like image 581
now he who must not be named. Avatar asked Nov 30 '22 04:11

now he who must not be named.


2 Answers

Advantage of the first method: It's case insensitive: If you get blue, and there's an enumeration member Blue, all will be fine.

Advantage of the second method: It's self-documenting: You don't really want to parse, you want to check whether there is an enum value defined with a given name. So, in the second case, the name of the method more closely matches your intent.

That said, if you want both advantages, use the first method and encapsulate it into a well-named method (e.g. IsEnumDefinedIgnoreCase).

like image 136
Heinzi Avatar answered Dec 13 '22 10:12

Heinzi


Also, be aware that the TryParse method will return true if you pass it an string including a number, e.g. "123".

like image 38
José Antonio Rodríguez Pascual Avatar answered Dec 13 '22 10:12

José Antonio Rodríguez Pascual