Mohsen Koorani
Mohsen Koorani

Reputation: 241

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

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?

Upvotes: 0

Views: 93

Answers (2)

Guru Stron
Guru Stron

Reputation: 143098

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 in runtime if Enum's 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).

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063864

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

Upvotes: 3

Related Questions