My series of posts on C# 6.0 has been on a long hiatus due to changes in the language feature set announced last year. Now with spring just around the corner in the northern hemisphere, Visual Studio 2015 reaching a 5th CTP status, and features hopefully stabilizing, it might be time to start up again.
As of C# version 5, there are many techniques you can use to avoid null reference exceptions (NREs). You can use brute force if else checks, the Null Object design pattern, or even extension methods, since extension method invocations will work on a null reference.
The conditional access operator, ?., adds one more option to the list for v6 of the language.
Imagine you are writing a method to log the execution of some code represented by an Action delegate. You aren’t sure if the caller will pass you a proper delegate, or if that delegate will have a method and a name.
The following code uses conditional access to retrieve the method name of an action, or “no name” if the code encounters a null value along the line.
public async Task LogOperation(Action operation) { var name = operation?.Method?.Name ?? "no name"; operation(); await _logWriter.WriteAsync(name + " executed"); // ... exception handling to come soon ... }
By dotting into the operation parameter using ?., you’ll be able to avoid NREs. ?. will only dereference a pointer if the pointer is non null. Otherwise, the operator will yield a null value.
By combining ?. with the null coalescing operator ??, you can easily specify defaults and write code that must be read using uptalk!
Next up in the series: await and exceptions.