Sunday, November 12, 2017

Null-conditional operator in C#

Null-conditional operator is a new .NET feature meant to ease your life as a developer. Its primary purpose is NullReferenceException prevention. I'mma give you an example:

namespace ConsoleApp
{
    class Car
    {
        public string Brand { get; set; }
    }

    class Program
    {
        static void DoSomethingWithCar(Car car)
        {
            // This is where you omitted check for null.
            string brand = car.Brand; // And this is where you get into trouble.
        }
        static void Main(string[] args)
        {
            DoSomethingWithCar(null);
        }
    }
}

Now we can either add missing check or use null-conditional operator:

namespace ConsoleApp
{
    class Car
    {
        public string Brand { get; set; }
    }

    class Program
    {
        static void DoSomethingWithCar(Car car)
        {
            // Null-conditional operator checks if car is null and if it is,
            // prevents us from accessing Brand property and sets brand to null.
            string brand = car?.Brand;
        }
        static void Main(string[] args)
        {
            DoSomethingWithCar(null);
        }
    }
}

Let's slightly modify our example so you can see another use case of null-conditional operator:

namespace ConsoleApp
{
    class Car
    {
        public string Brand { get; set; }
    }

    class Program
    {
        static void DoSomethingWithCars(Car[] cars)
        {
            // Null-conditional operator checks if cars array is null and if it is,
            // prevents us from accessing its first element and returns null.
            Car car = cars?[0];
        }
        static void Main(string[] args)
        {
            DoSomethingWithCars(null);
        }
    }
}

As you can see null-conditional operator can be used with both dot operator and subscript operator (square brackets).

2 comments:

  1. Классная штука, с какого С# она появилась?

    ReplyDelete
    Replies
    1. Если я не ошибаюсь впервые эта штука появилась в C#6.

      Delete