#TIL the Safe Navigation Operator

I learned today about the Safe Navigation Operator, and that we might be getting one in C#! I’m so excited!

For those who have no idea what I’m talking about, the Safe Navigation Operator is a way to traverse down an object graph without having to do null checks along the way. If you’re a software developer, you’ve probably run into this scenario:

1
2
3
4
5
6
var response = SomeWebAPI.GetData();
object[] actualDataIWant;
if(response != null)
    if(response.result != null)
      if(response.result.pages != null)
          actualDataIWant = response.result.pages[0].data;

Because each object in the graph could possibly be a null reference, we have to do a bunch of checks before we can safely assume the data we want to grab is there. With a Safe Navigation Operator, all of this is reduced to:

1
2
var response = SomeWebAPI.GetData();
var actualDataIWant = response?.result?.pages[0]?.data;

If any part of the object graph is null along the way, the “actualDataIWant” variable is just assigned null. No more dealing with NullReferenceExceptions, and no more complicated if statements for safety’s sake. How sweet is that?!

Apparently this has existed in Groovy for awhile, and as of the 25th the language team at Microsoft are “seriously considering this feature for C# and VB, and will be prototyping it in the coming months”. (source) I can’t wait to refactor ALL MY CODE!

Comments