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?);
Enum types cannot be nullable.
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With