Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.IsDefined returns false for strings

Tags:

c#

enums

I used the Enum.IsDefined() method for a string, but I get False in a situation where I think I should get True. Please check the below code:

public enum YourEnum : int
{
    Zero = 0,
    One = 1
}

public class Program
{

    public static void Main(string[] args)
    {
        Console.WriteLine(Enum.IsDefined(typeof(YourEnum), 1));
        Console.WriteLine(Enum.IsDefined(typeof(YourEnum), 1.ToString()));
    }
} 

C# Fiddle Demo
Result:

True
False

I don't know why should I get False in the second case. Any help is appreciated.

like image 620
shA.t Avatar asked Dec 31 '17 09:12

shA.t


People also ask

What is enum IsDefined?

Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not.

How do you check if a string is part of an enum C#?

In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum.

How to match string to enum c#?

TryParse() method converts the string representation of enum member name or numeric value to an equivalent enum object. The Enum. TryParse() method returns a boolean to indicate whether the specified string is converted to enum or not. Returns true if the conversion succeeded; otherwise, returns false .

Should I use enums or strings?

They are different types of data. Enums are way more efficient memory-wise. Use enums rather than strings, in this case. The difference in performance may be hardly noticeable but there is no reason to waste performance when you don't have to.


1 Answers

When you pass a string to the IsDefined() method, you are asking whether there is a value in the enum having that name. The documentation reads:

The value parameter can be any of the following:
• Any member of type enumType.
• A variable whose value is an enumeration member of type enumType.
The string representation of the name of an enumeration member. The characters in the string must have the same case as the enumeration member name.
• A value of the underlying type of enumType.

(emphasis mine)

It's a bit confusing to read, because the first, second, and fourth options above all result in the same thing: a value of the enum type being passed (boxed, of course).

But the third option is what's going on your scenario, and the string needs to match the name of an enum member. You're passing the string "1", and the only valid names in the enum are "Zero" and "One". The string "1" doesn't match either of those, so IsDefined() returns false.

like image 135
Peter Duniho Avatar answered Sep 28 '22 08:09

Peter Duniho