Wednesday, February 26, 2014

? for C#? (aka C# might be getting a object hierarchy Safe Navigation Operator)

Jerry Nixon @ Work - At last, C# is getting “?.”, sometimes called the Safe Navigation Operator

Visual Studio (and many other Microsoft Products) uses http://UserVoice.com as a feedback mechanism for users to suggest and vote on product features. One of the most popular features, with 3,752 votes, a new “?.” operator for the C# language, sometimes called the Safe Navigation Operator.

The news

Rejoice. Yesterday, Tuesday, February 25, 2014, on the Visual Studio User Voice, Mads Torgersen, the C# Language PM, responded on behalf of the Visual Studio Project Team. He said, “We are seriously considering this feature for C# and VB, and will be prototyping it in the coming months.” ...

...

What is it? Here’s the scenario

Consider getting the grandchild of a parent object like this:

var g1 = parent.child.child.child;

Okay, so, this is some poor coding because the value of child could be null....

...

How the new operator works

Consider getting the grandchild of a parent object like this:

var g1 = parent?.child?.child?.child;
if (g1 != null) // TODO

Wow! ...

...

Furthermore

Mad’s Visual Studio User Voice comment continued with a little more explanation of the operator’s implementation. He said, “If the type of e.x (etc) is a non-nullable value type S, then the type of e?.x is S?. Otherwise the type of e?.x is the same as that of e.×. If we can’t tell whether the type is a non-nullable value type (because it is a type parameter without sufficient constraints) we’ll probably give a compile-time error.” This comment, and the idea that a method call or indexer can be to the right of the operator are just candy.

image...

This operator would be pretty awesome and safe me a great deal of code... Wonder if we'll hear more about this at Build? Here's to hoping...

3 comments:

Anonymous said...

When I first heard of this feature for C# (I believe it's called Null Propagation, and if it isn't, that's what I'm calling it anyway), I immediately went to create a request on UserVoice to add it to Visual Basic as well. I've gotten positive feedback from the Visual Studio team in my request, and am quite excited to finally kill null reference exceptions without resorting to redundant If loops.

http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/5168168-add-null-propagating-member-access-operator-t

Chris said...

Um, Law of Demeter anyone?

Unknown said...

Agreed with Christopher. I foresee maintenance hell and TDD hell with this comfort feature.