If you’ve read blog posts or even MSDN articles explaining new features in C# 6.0 – I’m sure you’ve learned that the null-conditional operator in C# 6.0 will help you to greatly reduce the number of hard-to-debug and hard-to-reproduce NullReferenceException-s.
When I first read about this operator, the only thing that registered in my mind was that it helped you to chain null checks, especially for descending into data structures, and short-circuit the rest of the checks as soon as you hit null somewhere in the chain. So, I thought it was just a mere convenient syntactic sugar.
But I still did not completely understood the true power of this operator. I’m usually pretty meticulous about null checks and have a lot of C# 5.0 code like this:
private static int GetCurrentSpeed(Car car) { if (car != null && car.Engine != null && car.Engine.ControlUnit != null) { return car.Engine.ControlUnit.CurrentSpeed; } return 0; }
And I was debating whether it was worth it to go through the code base and refactor it to use null-conditional operator. Would I gain anything? Was it worth it just to have the code to look like this:
private static int GetCurrentSpeed(Car car) { return car?.Engine?.ControlUnit?.CurrentSpeed ?? 0; }
Okay, I cut 5 lines of code, what’s the big deal?