Next version of C# that will be coming with Visual Studio (supposedly version 2014) will have a new operator called the null-propagating operator (
?.) allowing us to write null conditional statement expressions. This will help us simplify our code tremendously by collapsing several lines of conditional blocks to a single statement. Combining it with null-coalescing operator makes it even more powerful as seen in this example:
string username = GetUser()?.name ?? "anonymous";Object will be null checked before trying to access its members so we'll avoid the infamous null reference exception. It will therefore automatically continue to null coalescing part of the statement. You can read more about it on this link.
null value checking code is something we frequently write at the beginning of method body to avoid null reference runtime exceptions. You know these
if statements right at the beginning of your methods:
1: public string DoSomething(Model data)
3: if (data == null)
5: throw new ArgumentNullException("data");
8: // actual processing
Even static code analysis tools complain if you don't do these checks and to be honest this is a very good practice to avoid many future bugs in your code. The problem isn't this code per se, but rather that we're writing these seemingly same lines over and over again. Many developers tried simplifying this process using different techniques but the one I'm going to show here is a bit different.