Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of IsDefined<TEnum>(TEnum value)?

Tags:

c#

enums

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

like image 345
Ashijo Avatar asked Sep 20 '25 13:09

Ashijo


1 Answers

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));
    }
}
like image 105
Ashijo Avatar answered Sep 22 '25 02:09

Ashijo