X

Null propagating operator in C#

C# 6.0 introduces language feature called null propagation. It’s about avoiding all this if-else mess in most sanity checks that avoid NullReferenceException.Of course, null checks can be found also from other parts of code that doesn’t necessarily deal with sanity checks. Let’s see how new null propagation feature help us write cleaner code.

Handling nulls

Let’s start with simple Person class.

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Person> Children { get; set; }
}

Let’s try to write out the name of first child if it exists or “-“ if person has no first child in Children collection. The code below introduces code that looks ugly because of null checks.

static void Main(string[] args)
{
    var customer = new Person { Name = "John Doe" };

    Console.Write("First child: ");

    if (customer.Children != null)
    {
        if (customer.Children.FirstOrDefault() != null)
        {
            Console.WriteLine(customer.Children.First().Name);
        }
        else
        {
            Console.WriteLine("-");
        }
    }
    else
    {
        Console.WriteLine("-");
    }

    Console.WriteLine("Press any key to exit …");
    Console.ReadLine();
}

Maybe some of us are not happy with code like this and write some methods to Person class to keep code more readable. But we are not still lucky because we just move the problem from one part of code to another.

All this code is about one thing: how to handle null in code so we don’t run into NullReferenceException.

For hardcore programmers.To avoid null objects Martin Fowler defined pattern called Special Case. Special Case is defined as a subclass that provides special behavior for particular cases. In some cases you can go with Special Case but don’t try to apply this pattern to all null object cases in your code.

But often we can’t go so complex because it’s not practical.

Null propagation

New C# makes handling null objects way easier for us. The following code does exactly the same thing as code above. Instead on if-else spaghetti we have nice readable code.

static void Main(string[] args)
{
    var customer = new Person { Name = "John Doe" };

    Console.Write("First child: ");
    Console.WriteLine(customer.Children?.FirstOrDefault()?.Name ?? "-");


    Console.WriteLine("Press any key to exit …");
    Console.ReadLine();
}

Question mark after property or method name means “stop here if value is null”. If you compare two versions of code you can see that null propagation helps to solve another code readability issue.

Liked this post? Empower your friends by sharing it!
Categories: .NET C#

View Comments (0)

Related Post