Search code examples
c#.netnullablec#-6.0null-conditional-operator

Does the "?." operator do anything else apart from checking for null?


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?


Solution

  • Because Nullable<T> is implemented in C# in a way that makes instances of that struct appear as nullable types. When you have DateTime? it's actually Nullable<DateTime>, when you assign null to that, you're setting HasValue to false behind the scenes, when you check for null, you're checking for HasValue, 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 to null-ness).