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)?
generics enums casting c # nullable
devuxer
source share