There are few C# features/.NET technologies that I really don’t like. Take WebForms and the ease of making the spaghetti-code there. Or the need of manually calling OnPropertyChanged in WPF. But maybe those are nat that bad and I don’t like people abusing/misusing them? I’m not sure. What I’m sure of is that null-conditional operator is joining the club.
Why this new feature is on my list you ask? Well, lets start by showing what’s its’ purpose. In theory it removes the need of extensive null checking.
Lets see the following example code
As string can be null we need to ensure that Substring is not called when the value is not provided. With the null-propagation operator we could shorten it to
It is also nice if you have dotted expression like this:
Well what to complain about you ask? Shorter and less code is always better. But maybe not? Well the problem is when people start overusing this operator.
Is this really an issue?
Yes, but only when when overused. How? Simply. Got NullReferenceException? Just use ?. and you’re done, finito. To be fair – it will solve the issue but in few cases only by hiding the exception. In few rare cases the error is elsewhere and here, where the null-propagation operator is used, the object should never be null. The proper way should be to investigate and maybe add an assert in the method to get that condition checked properly.
null-conditional can be helpful operator but only when used cautiously. So before the next time you are urged to type ? followed by a dot – just think about it twice before doing it. You can thank me later.
More about this operator can be found on MSDN.
Founder of Octal Solutions a .NET software house.
Passionate dev, blogger, occasionally speaker, one of the leaders of Wroc.NET user group. Microsoft MVP. Podcaster – Ostrapila.pl