C# 6.0 – Null-Conditional Operators

This is another post in the series on the new features that are coming in C# 6.0.

This is one of my favourite new features. Have you ever written code like this?

if (line != null && line.Product != null)
{
    total += line.Product.Price * line.Quantity;
}

C# 6.0 introduces the ?. null-conditional operator that short circuits and returns null if anything in the chain is null. This combines really well with the null-coalescing operator allowing you to rewrite the above as follows.

total += line?.Product?.Price ?? 0 * line?.Quantity ?? 0;

This also works with indexers,

var firstProduct = OrderLines?[0].Product;	// Will return null if OrderLines is null

It also works with methods. This will be really handy for triggering events. Instead of writing,

if (OrderChanged != null)
{
    OrderChanged(this, EventArgs.Empty);
}

You will now be able to write.

OrderChanged?.Invoke(this, EventArgs.Empty);

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.