null conditional operator not working with nullable types?

Solution 1:

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();

Solution 2:

The reason for this is that accessing the value with a null conditional operator would be pointless:

  • When you apply x?.p where p is a non-nullable value type T, the result is of type T?. By the same token, the result of nullableInt?.Value operation must be nullable.
  • When your Nullable<T> has a value, the result of nullableInt?.Value would be the same as the value itself
  • When your Nullable<T> does not have a value, the result would be null, which is, again, the same as the value itself.

Although it does not make sense to access Value with the ?. operator, it does make sense to access other properties of nullable value types. The operator works consistently with nullable value types and with reference types, so these two implementations produce identical behavior:

class PointClass {
    public int X { get; }
    public int Y { get; }
    public PointClass(int x, int y) { X = x; Y = y; }
}
struct PointStruct {
    public int X { get; }
    public int Y { get; }
    public PointStruct(int x, int y) { X = x; Y = y; }
}
...
PointClass pc = ...
PointStruct? ps = ...
int? x = pc?.X;
int? y = ps?.Y;

In case of a nullable struct the operator lets you access a property of the underlying type PointStruct, and it adds nullability to the result in the same way that it does for non-nullable properties of the reference type PointClass.