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?
The ?? operator is used to check null values and you can also assign a default value to a variable whose value is null(or nullable type).
The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
A null coalescing operator, in C#, is an operator that is used to check whether the value of a variable is null.
The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null , the rest of the chain doesn't execute.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With