Live data from Hacker News

C# is getting “?.”, sometimes called the Safe Navigation Operator

blogs.msdn.com

11–12 of 12 posts

Re: C# is getting “?.”, sometimes called the Safe Navigation Operator

#11
post #8

Earlier quoted context omitted.

Using ?. lets you do code like: var = foo()?.bar?.bing() if(foo==null){...} instead of putting a null check between every call. In many cases null is used to indicate that a computation failed. If you are doing a chain of computations, there is often not a reason you need or want to do a check between every computation, instead of having a single handler at the end for if any of them fail. This pattern comes up fairl…

There are certain languages and situations where the pattern does make sense. But as a heavy C# coder, I find that more often than not you're dealing with a class heavy codebase where it's more important that you _don'_ do foo()?.bar?.bing(). Specifically as things happen such as refactoring you often need to ask the question should something 'care' that a foo has a bar which has a bing. Perhaps if you want to know a…

Yes, you could do that, but it goes against how everybody has been accessing object properties for the past two decades.

Quite often, you simply want person.address.street.number, and if it doesn't exist, you simply go on without it, and it doesn't matter what the exact reason is why it doesn't exist. This is an extremely common and practical pattern, and it's hindered by layers of null pointer checks.

Re: C# is getting “?.”, sometimes called the Safe Navigation Operator

#12
Great news. The ?. operator in Groovy greatly reduces boilerplate code and improves readability and maintainability. No layers of null pointer checks that are all basically the same and getting in the way of what you actually want to do.

And in those cases where you still need specific behaviour based on which object is null, you can still use the . operator with traditional null pointer checks.

Post reply on HN