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?
Best Answer
Okay, I have done some thinking and testing. This is what happens:
Gives this error message when compiling:
That means that
?
'converts' theint?
into the actualint
value. This is effectively the same as:The result is an integer, which doesn't have a
Value
, obviously.Okay, might this help?
No, that syntax isn't allowed.
So what then? Just keep using
.GetValueOrDefault()
for this case.