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:
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.
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