In a previous article I explained the C# 6 string interpolation which is really a great enhancement with C# 6. With this follow-on article I’m showing another great C# 6 feature: the null conditional operator (also known as null propagation operator or the Elvis operator).
The operator is known as Elvis operator because the operator ?. looks like Elvis’ hairstyle.
A program usually consists of many code lines just with null checks. Using the null conditional operator, the number of code lines can be reduced and it also becomes a lot easier to read.
Overview
Instead of checking if a received object is null and returning,…
public void ShowPerson(Person p) { if (p == null) return; string firstName = p.FirstName; //... }
…the code can be simplified using ?. like this:
public void ShowPerson(Person p) { string firstName = p?.FirstName; //... }
Instead of throwing a NullReferenceException
with the . operator, ?. returns null. If the left side of the ?. operator returns null, the result of the statement is null. If the left side of the operator is not null, the statement continuous to the right – and in this case accesses the FirstName
property and returns the value of this property.
A statement using the conditional operator such as this
int? age = p == null ? null : p.Age;
…can be simplified:
int? age = p?.Age;
The null conditional operator ?. reduces the code lines, and makes the code easier to understand because the null checks do not pollute your important code that is relevant to the functionality.
Together with the Coalescing Operator
In case the variable firstName
shouldn’t be null but instead should contain an empty string, the null conditional operator works great in combination with the coalescing operator:
public void ShowPerson(Person p) { string firstName = p?.FirstName ?? string.Empty; //... }
The null conditional operator becomes very useful in combination with the coalescing operator ??
Null Propagation with Arrays
Null checks using the null conditional operator can also be done with arrays. If the array variable arr
is null, ?[ returns null, and then the coalescing operator comes into play, and 0 is assigned to x1
. If arr
is not null, the first element of the array is returned and assigned to the x1
variable:
int[] arr = { 1, 2, 3 }; int x1 = arr?[0] ?? 0;
Simplifying Firing Events
The C# 6 syntax also becomes very handy when firing events. Instead of writing
public event EventHandler<CarInfoEventArgs> NewCarInfo; private void OnNewCarInfo(string car) { EventHandler<CarInfoEventArgs> handler = NewCarInfo; if (handler != null) { handler(this, new CarInfoEventArgs(car)); } }
the code can be simplified, and it is still thread-safe:
public event EventHandler<CarInfoEventArgs> NewCarInfo; private void OnNewCarInfo(string car) { NewCarInfo?.Invoke(this, new CarInfoEventArgs(car)); }
Event handling can be greatly simplified using the null propagation operator
A Simplified CanExecute
An example from a DelegateCommand class implementation, previously to C# 6 the CanExecute method looked like the following code snippet. If _canExecute is not assigned, the method CanExecute returns true. In case a delegate is assigned, the delegate is invoked, and the result is returned from CanExecute:
public bool CanExecute(object parameter) { if (_canExecute == null) return true; return _canExecute(); }
Multiple C# 6 features are used to simplify this code snippet. Using ?., if _canExecute returns null, the coalescing operator takes action, and true is returned. If _canExecute is not null, the Invoke method of the delegate is called. You just can’t use parentheses directly using the null conditional operator like _canExecute?.(). That’s why the Invoke method is called explicitly. In the previous code snippet, the compiler created code to call the Invoke method as well. Because the resulting code with the null conditional operator consists of a single statement, an expression bodied member can be used to get rid of the curly brackets and the return keyword.
public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;
Summary
The null conditional operator that is new since C# 6 is a great enhancement for C#. The number of code lines can be reduced, and the code gets more readable as well.
More Information
My book Professional C# 6 and .NET Core 1.0 covers this operator in chapter 6, Operators and Casts, and it is used throughout the book in many code samples. Of course in the book you’ll also read about all the other C# 6 features such as static using, expression bodied members, auto implemented property initializers, read-only auto properties, and more. Of course, this information is also covered in my workshops.
Have fun with programming and learning!
Christian
CN innovation
7 thoughts on “C# 6 – Null-Conditional Operator”