Conditional Access Operator in C# 6.0

Thursday, February 12, 2015

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.


Comments
gravatar Kent Thursday, February 12, 2015
You might want a null check before invoking the delegate though 😉
Betty Friday, February 13, 2015
operation?.Invoke();
gravatar Scott Friday, February 13, 2015
Yes, more code with this sample to come ....
gravatar Anders Lybecker Saturday, February 14, 2015
Chained null checks is an awesome feature; especially when implementing event handlers. See my blog post: http://www.lybecker.com/blog/2015/01/06/chained-null-checks/
Sunday, February 15, 2015
A nice post from the skeet: http://codeblog.jonskeet.uk/2015/01/30/clean-event-handlers-invocation-with-c-6/
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!