Search code examples
c#intnullableenumeration

Convert between nullable int and int


I would like to do something like this :

int? l = lc.HasValue ? (int)lc.Value : null; 

where lc is a nullable enumeration type, say EMyEnumeration?. So I want to test if lc has a value, so if then give its int value to l, otherwise l is null. But when I do this, C# complains that 'Error type of conditional expression cannot be determined as there is no implicit conversion between 'int' and ''.

How can I make it correct? Thanks in advance!!


Solution

  • You have to cast null as well:

    int? l = lc.HasValue ? (int)lc.Value : (int?)null; 
    

    By the way, that's one of the differences between the conditional operator and an if-else:

    if (lc.HasValue)
        l = (int)lc.Value;
    else
        l = null;  // works
    

    The relevant C# specification is 7.14 Conditional operator:

    The second and third operands, x and y, of the ?: operator control the type of the conditional expression.

    • If x has type X and y has type Y then
      • If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
      • If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
      • Otherwise, no expression type can be determined, and a compile-time error occurs.

    Since int is not convertible to null implicitly and vice-versa you get a compiler error. But you could also cast the enum to int? instead of int which is convertible. Then the compiler can derive the type and it'll compile:

    int? l = lc.HasValue ? (int?)lc.Value : null; // works also
    

    or, as Sergey has mentioned in his answer, directly:

    int? l = (int?)lc;