As you might know, DateTime?
does not have a parametrized ToString
(for the purposes of formatting the output), and doing something like
DateTime? dt = DateTime.Now;
string x;
if(dt != null)
x = dt.ToString("dd/MM/yyyy");
will throw
No overload for method 'ToString' takes 1 arguments
But, since C# 6.0 and the Elvis (?.
) operator, the above code can be replaced with
x = dt?.ToString("dd/MM/yyyy");
which.... works! Why?
Because
Nullable<T>
is implemented in C# in a way that makes instances of that struct appear as nullable types. When you haveDateTime?
it's actuallyNullable<DateTime>
, when you assignnull
to that, you're settingHasValue
tofalse
behind the scenes, when you check fornull
, you're checking forHasValue
, etc. The?.
operator is just implemented in a way that it replaces the very same idioms that work for reference types also for nullable structs. Just like the rest of the language makes nullable structs similar to reference types (with regard tonull
-ness).