Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 204
iuliu.net Avatar asked Jan 29 '16 10:01

iuliu.net


People also ask

Which operator is used with null operator?

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).

How do you use the null operator?

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.

What is a null coalescing operator used for?

A null coalescing operator, in C#, is an operator that is used to check whether the value of a variable is null.

What is null conditional?

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.


1 Answers

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).

like image 160
Joey Avatar answered Sep 23 '22 01:09

Joey