Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# cast object of type int to nullable enum

Tags:

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!! 
like image 749
dlsou Avatar asked Mar 04 '11 21:03

dlsou


2 Answers

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.

like image 80
Jon Skeet Avatar answered Oct 19 '22 15:10

Jon Skeet


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.

like image 43
Reed Copsey Avatar answered Oct 19 '22 15:10

Reed Copsey