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.
You're working with boxed int
value. Unbox it back into int
first:
var en = (Digits?) (int) obj; // note "(int)"
If obj
can be assigned to null
you can use ternary operator:
Digits? en = null == obj ? null : (Digits?) (int) obj;
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