Tryparse and IsDefined for Enum in C#

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 ?

Upvotes: 6

Views: 6807

Answers (3)

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

Upvotes: 10

Heinzi
Heinzi

Reputation: 172220

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).

Upvotes: 12

Habib
Habib

Reputation: 223207

In first case if your parsing is successful then you will get the enum value in evalue. You are also passing true for ignore case parameter, so the comparison will ignore the case of the string. The way you have it now, it would return true in success and discard the value in evalue.

In 2nd code you are only checking if the enum is defined or not.

Upvotes: 1

Related Questions