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