C# 6.0 New Features - Null-Conditional Operators

development, csharp comments edit

This is another handy feature. Checking for null values before accessing them can quickly become cumbersome and yields a lot of boilerplate code. With this new operator checking for nulls and coalescing becomes really short and easy to read.

For example:

public class NullConditionalOperators
{
    public void Run()
    {
        Person person = GetPerson();

        // Current C#
        if (person != null && person.Country != null)
        {
            Console.WriteLine(person.Country.Name);
        }
        else
        {
            Console.WriteLine("Undefined");
        }
    }

    private Person GetPerson()
    {
        return new Person() { Firstname = "Volkan", Lastname = "Paksoy" };
    }
}

public class Person
{
    public string Firstname { get; set; } = "Unknown";
    public string Lastname { get; set; } = "Unknown";
    public Country Country { get; set; }
    
}

public class Country
{
    public string Name { get; set; }
    public string IsoCode { get; set; }
}

In the example above if you need to print the name of the country first you need to ensure both the Person and Country objects are not null. The if block aobe can be reduced to a one-liner with 6.0:

	Console.WriteLine(person?.Country?.Name ?? "Undefined");

They both produce the same results. The more complex the object hierarchy becomes the more useful this feature would be.

Comments