Null-conditional operators in C# 6

This is the seventh part of a series of posts I’m making into Upcoming Language Feature Changes in C# 6. (Now Visual Studio 2015 is available, they’re not so “upcoming”).

I’m going to come straight out and say that this is my favourite new language feature in C# 6. It’s going to get used a lot and will save a lot of typing and make the code a lot more readable. Basically, this is another productivity boost – a common feature of C# 6 – and I’m sure something a lot of us will welcome.

Example Classes

For the examples I’ll be using, I’ve imagined some strange car insurance system where a car can only have 1 accident and each accident needs only 1 part to replace.

public class Car
    public string Registration { get; set; }

    public int? Age { get; set; }

    public Accident Accident { get; set; }

public class Accident
    public string Reason { get; set; }

    public Part ReplacedPart { get; set; }

public class Part
    public int Price { get; set; }

    public string Name { get; set; }

Obviously not realistic, but I’m hoping once you see the example you can see how this feature will work with any code bases you’re familiar with.

Basic Null-Conditional Operator

To prevent NullReferenceExceptions, you will often see code which makes sure something isn’t null, then does access a property

    string result = null;

    if (car != null)
        result = car.Registration.Substring(0, 2);

    return result;

The null-conditional operator – ?. – helps make that code much more succinct.

public string FirstTwoCharactersOfRegCSharp6(Car car)
    return car?.Registration.Substring(0, 2);

The above code is checking that car is not null before accessing the Registration property and will evaluate to null if it is.


It doesn’t end there as you’re not limited to one null-conditional operator, so you can wave goodbye to the days of “Christmas Tree” code where you have multiple levels of if-else.

	return car?.Accident?.ReplacedPart?.Name

Like above, if at any point the property is null, the whole expression results in null.

Combined with Null Coalescing operator

Finally, you can combine this with existing features of the language for yet more neat code.

	var replacedPart = car?.Accident?.ReplacedPart?.Name ?? "Name not specified";


Like I said above, this is probably my favourite feature of C# 6. The code we write should be more elegant to produce, easier to read and therefore hopefully less error prone.

I confess to leaving off too many null pointer checks because I’m in the zone and a.n.other if-else feels like a pain, but now I have no excuse.

Leave a Reply

Your email address will not be published. Required fields are marked *