I just need to be able to cast an object to nullable enum. Object can be enum, null, or int. Thanks!
public enum MyEnum { A, B }
void Put(object value)
{
System.Nullable<Myenum> val = (System.Nullable<MyEnum>)value;
}
Put(null); // works
Put(Myenum.B); // works
Put(1); // Invalid cast exception!!
How about:
The cast from boxed
inttoMyEnum(ifvalueis non-null) and then use the implicit conversion fromMyEnumtoNullable<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.