Short answer:
DateTime?
is only a sweet syntax for Nullable<DateTime>
which doesn't contain DateTime
's properties and method while the Elvis operator works on the not-Nullable Nullable<DateTime>.Value
.
Explanation:
The following code:
DateTime? dt = DateTime.Now;
string x;
if (dt != null)
x = dt?.ToString("dd/MM/yyyy");
When decompiles as C# 5.0
yields the following result:
DateTime? nullable = new DateTime?(DateTime.Now);
if (nullable.HasValue)
{
string str = nullable.HasValue ? nullable.GetValueOrDefault().ToString("dd/MM/yyyy") : null;
}
Side note: the string
seems declared inside the if
is irrelevant because of hoisting at the MSIL
level, and since the value is not used later on the decompiler shows it as if it was declared inside that if
scope.
As you see, and since DateTime?
is only a sweet syntax for Nullable<DateTime>
, C#
has a specific reference for Nullable<T>
s with the Elvis operator, making its return value the non-nullable T itself.
The result of the whole Elvis operator
must be Nullable
therefore, if you wanted to receive a non-string
value it would have to be either Nullable<T>
or a ReferenceType
but this doesn't change the fact that if the operator has managed to get the Nullable<DateTime>
value itself - the returned DateTime
is not Nullable<DateTime>
anymore.