InvalidCastException tries to throw from nested int to null enumeration

I have an enumeration, Foo :

 public enum Foo { Alpha, Bravo, Charlie } 

Should I try the following selection from a placed int in Foo? I get an InvalidCastException :

 var x = (Foo?)(object)1; 

This led me to some experiments ...

 var x = (Foo)(object)1; // succeeds var x = (long)(object)1; // fails var x = (long?)(object)1; // fails var x = (long)1; // succeeds var x = (long?)1; // succeeds var x = (int)(object)1; // succeeds var x = (int?)(object)1; // succeeds 

This suggests that you can cast from a boxed int to an enumeration, but not to long , and you cannot convert from a boxed int to any type nullable except int? .

By the way, the reason I am throwing int into object is because I am really trying to make the general TValue parameter from int , for example:
 var x = (TValue)(object)1; 

If I did not have (object) , it will not compile. (For more, see Eric Lippert's This Blog )

Questions

  • Why can you convert from a boxed int to enum, but not to a null enumeration (and not to long and a long? )?

  • What is the easiest way to rewrite var x = (TValue)(object)1; so that it compiles, runs at runtime, and is performative (assuming TValue is defined as Foo? at runtime)?

+5
generics enums casting c # nullable
source share
2 answers

To answer the first question, you can convert from a value in a box to an enumeration only if the nested value is of the rename type. If you announced

 enum Foo : byte { ... 

you cannot drop from a nested package in Foo.

To answer the second question, try

 var x = (TValue)Enum.ToObject(typeof(TValue), 1); 

This is due to boxing; if you need a solution that will not be in the box, it will be more difficult.

+5
source share

Nullables is not some special category of atomic types, but an abbreviation of type Nullable<T> , so you cannot insert int into a null enumeration box. If you want to create a null enumeration, you can do it like this:

 var x = new Nullable<Foo>((Foo)1); 

This answers your questions, I think!

+1
source share

All Articles