Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to nullable enum [duplicate]

Tags:

c#

enums

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.

like image 370
Seven Avatar asked Sep 10 '15 09:09

Seven


Video Answer


1 Answers

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;
like image 151
Dmitry Bychenko Avatar answered Sep 30 '22 19:09

Dmitry Bychenko