6

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.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Seven
  • 805
  • 12
  • 17

1 Answers1

8

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;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215