68

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?

tkocmathla
  • 901
  • 11
  • 24
  • 11
    nullcheck i assume.. – ddavison Aug 07 '14 at 18:29
  • Does anyone have another link for that "Pattern Matching in C#" draft spec, that isn't on a MSN OneDrive? The link is broken behind some corporate proxies. :( – RLH Aug 08 '14 at 11:22
  • Does this answer your question? [What does question mark and dot operator ?. mean in C# 6.0?](https://stackoverflow.com/questions/28352072/what-does-question-mark-and-dot-operator-mean-in-c-sharp-6-0) – Heretic Monkey Mar 29 '22 at 17:31

3 Answers3

97

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.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • 66
    I've been waiting for this for ages – romanoza Aug 07 '14 at 18:48
  • 12
    It's worth noting that x.y will only be evaluated once using the new syntax but twice using the current equivalent (assuming x and x.y are non-null). – petelids Aug 07 '14 at 19:38
  • 3
    The indentation makes your answer difficult to read. I for one would indent the colon on the same column as the matching question mark. – Kijewski Aug 08 '14 at 02:25
  • 2
    @Kay: If that's how the style guide works chez vous, you're welcome to do it however you want. :-) – StriplingWarrior Aug 08 '14 at 02:38
  • 1
    So when can Java programmers expect this sort of functionality? – RevanProdigalKnight Aug 08 '14 at 11:50
  • 2
    @RevanProdigalKnight it's not scheduled for java 8 and java 9, so I guess in like next 10 years. – om-nom-nom Aug 08 '14 at 13:32
  • @om-nom-nom I actually asked one of my coworkers about this; it was apparently suggested for Java 6 or 7 but Oracle said "No, we can't make language-level changes" ind introduced the [Optional](http://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) class as an alternative. Suffice it to say that it's nowhere near as nice as being able to just use `x?.y?.z;` – RevanProdigalKnight Aug 08 '14 at 13:41
  • @RevanProdigalKnight Although `Optional.flatMap` isn't as nice as `x?.y?.z`, it sure is nice to not have the code blow up in random places because `null` was being passed around. So I guess it depends on what you consider nicer. – Doval Aug 08 '14 at 15:24
  • @RevanProdigalKnight, only using [Groovy](http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28?.%29), which, i think, created it, but i have no backing resources to it. Otherwise, Optional on [Java 8](http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html) or [Scala](http://www.tutorialspoint.com/scala/scala_options.htm) – Will Aug 08 '14 at 17:16
  • 1
    @Doval, Actually, I think the *best* thing would have been if reference types weren't allowed to be null in the first place, unless you added a `Nullable<>` around them. I agree, though, about how nice it is to avoid null reference exceptions. I even created a library, [Call Me Maybe](https://bitbucket.org/j2jensen/callmemaybe) to provide an equivalent of `Optional` for C#. Point being, I think the language feature and an `Optional` type can complement each other--they shouldn't be mutually exclusive. – StriplingWarrior Aug 08 '14 at 20:42
  • 1
    @StriplingWarrior Agreed. Seems like an awful lot of work for something so specific though. You could get much more mileage out of something like Haskell's *do notation*. – Doval Aug 09 '14 at 01:53
  • 1
    I wonder how useful would it be to implement something like this to ECMAscript. I wouldn't say no to having something like this in JS. – Henrik Peinar Aug 12 '14 at 21:55
  • var exclamation = THIS?.Is?.SPARTA; – kingdango Aug 14 '14 at 18:57
  • var nonNullableInt = x?.y?.z ?? 0; – kingdango Aug 14 '14 at 18:59
29

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
Habib
  • 219,104
  • 29
  • 407
  • 436
  • I'd add that this is a C# 6 feature. – dee-see Aug 07 '14 at 18:30
  • 5
    @tkocmathla Nope, `??` is quite different: `x ?? y` is like `x != null ? x : y`. And `x?.y` is like `x != null ? x.y : null`. – Tim S. Aug 07 '14 at 18:32
  • 1
    @Habib Its still wrong "if x is not null, return y otherwise return null,". This does not return y, it either returns x.y.z or null. – mclaassen Aug 07 '14 at 18:41
  • 1
    @mclaassen, may be I am explaining considering them two different steps. The ultimate return value would be either `z` or `null` – Habib Aug 07 '14 at 18:42
3
 this.SlimShadies.SingleOrDefault(s => s.IsTheReal)?.PleaseStandUp();

Basically.

Phil
  • 1,062
  • 1
  • 17
  • 15