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 ?
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
).
Also, be aware that the TryParse method will return true if you pass it an string including a number, e.g. "123".
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