Home > Mobile >  Is there any way to make a generic method with Nullable<T> as parameter?
Is there any way to make a generic method with Nullable<T> as parameter?

Time:12-08

I have this method:

public T ToEnumTypeOf<T>(this int enumValue, T dest) where T : Enum 
    => (T)(object)enumValue

I want to change it to take Nullable as parameter. like:

public T ToEnumTypeOf<T>(this int enumValue, Nullable<T> dest) where T : Enum 
    => (T)(object)enumValue

Is there any way to do this?

CodePudding user response:

where T : Enum basically doesn't work as you expect; it isn't "any concrete enum", since Enum itself must work. The closest you can get is where T : struct, and check typeof(T).IsEnum

CodePudding user response:

Add struct generic constraint:

T ToEnumTypeOf<T>(int enumValue, T? dest) where T : struct, Enum
    => (T)(object)enumValue;

Compiler does not assume struct constraint for System.Enum one automatically. See examples from breakdown of new generic constraints in C# 7.3.

Note that this will fail if underlying type is not int:

enum MyEnum : byte
{
    One = 1
}

MyEnum dest = default;
ToEnumTypeOf<MyEnum>(1, dest); // Unable to cast object of type 'System.Int32' to type 'MyEnum'

Quick and dirty approach to fix this conversion via string (though not very performant one):

T ToEnumTypeOf<T>(int enumValue, T? dest) where T : struct, Enum
    => Enum.Parse<T>(enumValue.ToString());

Note that this will not throw for invalid enum values (as your current code, i.e. ToEnumTypeOf<MyEnum>(2, dest) will work just fine for example above).

  • Related