What does x?.y?.z mean?

C#Pattern Matching

C# Problem Overview

The draft spec for Pattern Matching in C# contains the following code example:

Type? v = x?.y?.z; 
if (v.HasValue) {
    var value = v.GetValueOrDefault();     
    // code using value 

I understand that Type? indicates that Type is nullable, but assuming x, y, and z are locals, what does x?.y?.z mean?

C# Solutions

Solution 1 - C#

Be aware that this language feature is only available in C# 6 and later.

It's effectively the equivalent of:

x == null ? null
   : x.y == null ? null
   : x.y.z

In other words, it's a "safe" way to do x.y.z, where any of the properties along the way might be null.

Also related is the null coalescing operator (??), which provides values to substitute for null.

Solution 2 - C#

It is Null-propagating operator / Null-Conditional Operator ?. a new proposed feature in C# 6.0

x?.y?.z means

  • first, check if x is not null, then check y otherwise return null,

  • second, when x is not null then check y, if it is not null then return z otherwise return null.

The ultimate return value will be z or null.

Without this operator if x is null, then accessing x.y would raise a Null Reference Exception, the Null-Conditional operator helps to avoid explicitly checking for null.

It is a way to avoid Null Reference Exception.

See: Getting a sense of the upcoming language features in C#

> 8 - Null-conditional operators > > Sometimes code tends to drown a bit in null-checking. The > null-conditional operator lets you access members and elements only > when the receiver is not-null, providing a null result otherwise:

int? length = customers?.Length; // null if customers is null

Solution 3 - C#

 this.SlimShadies.SingleOrDefault(s => s.IsTheReal)?.PleaseStandUp();



All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontkocmathlaView Question on Stackoverflow
Solution 1 - C#StriplingWarriorView Answer on Stackoverflow
Solution 2 - C#HabibView Answer on Stackoverflow
Solution 3 - C#PhilView Answer on Stackoverflow