C# cast object of type int to nullable enum

How about:

MyEnum? val = value == null ? (MyEnum?) null : (MyEnum) value;

The cast from boxed int to MyEnum (if value is non-null) and then use the implicit conversion from MyEnum to Nullable<MyEnum>.

That's okay, because you're allowed to unbox from the boxed form of an enum to its underlying type, or vice versa.

I believe this is actually a conversion which isn't guaranteed to work by the C# spec, but is guaranteed to work by the CLI spec. So as long as you're running your C# code on a CLI implementation (which you will be :) you'll be fine.


This is because you're unboxing and casting in a single operation, which is not allowed. You can only unbox a type to the same type that is boxed inside of the object.

For details, I recommend reading Eric Lippert's blog: Representation and Identity.

Tags:

C#

Enums

Nullable