In enum.cs
there are two implementation of enum.IsDefined
, the first one I always use is IsDefined(Type enumType, object value)
and it works perfectly fine.
But there is an other IsDefined
, this one :
public static bool IsDefined<TEnum>(TEnum value) where TEnum : struct, Enum
{
RuntimeType enumType = (RuntimeType)typeof(TEnum);
ulong[] ulValues = Enum.InternalGetValues(enumType);
ulong ulValue = Enum.ToUInt64(value);
return Array.BinarySearch(ulValues, ulValue) >= 0;
}
source : Enum.cs
Is there any way this method could return false ?
It looks like a bug to me, this function should accept an Enum in parameter, not a TEnum. Or am I completely missing the point here ?
I would expect this function to work just like the overload, just being a syntactic sugar
Thanks to Etienne de Martel
Yes it can return false, the idea is to cast before checking if the value is defined :
using System;
public enum E
{
V = 0
}
public class Program
{
public static void Main()
{
E e = (E)1;
Console.WriteLine(Enum.IsDefined(e));
}
}
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