Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Type of Nullable<Enum>?

Tags:

c#

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?);
like image 277
devlife Avatar asked Jun 13 '12 13:06

devlife


People also ask

Can an enum type be null?

Enum types cannot be nullable.

Can enum type be null C#?

An enum value cannot be null. It is a value type like an int. To avoid the "cannot convert null" error, use a special None constant as the first enum item.

Can enum return null?

There are multiple enum fields with this operation, if one of them does not have a value then a NULL value is returned which causes an exception to be thrown.

How do you make an enum Nullable?

“how to make enum nullable” Code Answer That being said you can use the built in Nullable<T> class which wraps value types such that you can set them to null, check if it HasValue and get its actual Value. (Those are both methods on the Nullable<T> objects. Nullable<Color> color = null; //This will work.


1 Answers

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.

like image 148
Marc Gravell Avatar answered Oct 22 '22 00:10

Marc Gravell