Search code examples
c#null-coalescing-operatorc#-6.0

null conditional operator not working with nullable types?


I'm writing a piece of code in c#6 and for some strange reason this works

var value = objectThatMayBeNull?.property;

but this doesn't:

int value = nullableInt?.Value;

By not works I mean I get a compile error saying Cannot resolve symbol 'Value'. Any idea why the null conditional operator ?. isn't working?


Solution

  • Okay, I have done some thinking and testing. This is what happens:

    int value = nullableInt?.Value;
    

    Gives this error message when compiling:

    Type 'int' does not contain a definition for `Value'

    That means that ? 'converts' the int? into the actual int value. This is effectively the same as:

    int value = nullableInt ?? default(int);
    

    The result is an integer, which doesn't have a Value, obviously.

    Okay, might this help?

    int value = nullableInt?;
    

    No, that syntax isn't allowed.

    So what then? Just keep using .GetValueOrDefault() for this case.

    int value = nullableInt.GetValueOrDefault();