devlife
devlife

Reputation: 16145

How to get Type of Nullable<Enum>?

How can you do something like the following in C#?

Type _nullableEnumType = typeof(Enum?);

I guess a better question is why can't you do that when you can do this:

Type _nullableDecimalType = typeof(decimal?);

Upvotes: 8

Views: 1209

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063559

Enum is not an enum - it is the base-class for enums, and is a reference-type (i.e. a class). This means that Enum? is illegal, as Nullable<T> has a restriction that T : struct, and Enum does not satisfy that.

So: either use typeof(Nullable<>).MakeGenericType(enumTypeKnownAtRuntime), or more simply, typeof(EnumTypeKnownAtCompileTime?)

You might also want to note that:

Enum x = {some value};

is a boxing operation, so you should usually avoid using Enum as a parameter etc.

Upvotes: 15

Related Questions