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

Time:12-17

In enum.cs there are two implementation of enum.IsDefined, the first one I always use is IsDefined(Type enumType, object value) 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 synthaxic sugar

CodePudding user response:

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));
    }
}

CodePudding user response:

The version that accepts object is OK, but it forces a "boxing" operation, i.e. it forces a heap allocation. In isolation, affordable, but: allocations add up. At the time, .NET didn't have generics, so: it was the best that could be done.

Generics serves as a mitigation against boxing (for value-types), so here it is used to avoid that overhead. It also makes calling it easier, since you don't need to specify the type at all in most cases (except perhaps when passing the literal zero). The compiler can infer the generics from the type of the argument.

  • Related