New operator in C#

Published on 2024-11-23 by Raul

The popular language, which I am a fan of, is getting a new operator: ?.

In the past, and also now, doing:

parent.firstChild.secondChild.lastChild

will throw a NullReferenceException if firstChild or secondChild is null.

With the new operator, you won't have to do null checks for each item in the list, they will be done automatically.

So you will be able to write:

parent?.firstChild?.secondChild?.lastChild

 without having to worry that any of the items are null. If they are, the final result of the expression will be null, but no exception will be thrown.

You can find the announcement here and the feature request on user voice.


Keep in touch


About

Hey there, I'm Raul, owner of CreativeCLR, a small consulting company.

Feel free to drop me any question you might have on this post using the comment section or the contact page.