I have a question about casting to nullable enum. Here is a code:
enum Digits
{
One = 1,
Two = 2
}
void Main()
{
int one = 1;
object obj = one;
var en = (Digits?) obj;
Console.WriteLine(en);
}
It gives me InvalidCastException
in line #11.
But if I omit '?' symbol in that line, it gives correct result "One" but I don't want to lose 'nullability'.
As a workaround I now use var en = (Digits?) (int?) obj;
and it works although I'm not sure of full correctness of such a solution.
But I wonder why does casting to nullable enum fail in the first case?
I expected that casting to nullable types acts as follows:
- cast to non-nullable type, if success then cast to nullable type
- if null
is passed then result would be null
as well
But it seems to be not true.