8.0 Null Coalescing Operator

File Location

  1. Right click on your solution

  2. Go to Add > New Project and select Console App (.NET Framework)

  3. Name it Null

Discussion

The C# Null Coalescing Operator ?? is a binary operator that simplifies checking for null values. It can be used with both nullable types and reference types. It is represented as x ?? y which means if x is non-null, evaluate to x; otherwise, y.

In the syntax x ?? y: 1. X is the first operand which is a variable of a nullable type. 2. Y is the second operand which has a non-nullable value of the same type.

Null coalescing operators are evaluated from right to left. If you have the expression x ?? y ?? z it will be read as x ?? (y ?? z)

Null coalescing operators can be used in place of some if else statements such as the one below. The first example will be with an if else statement and the second example will be with the null coalescing operator.

    class Program
    {
        static void Main(string[] args){
            int? a = null;
            int b;
            if (a.HasValue)
                b = a.Value;
            else
                b = 0;
            Console.WriteLine("Value of b is {0} ", b);
            Console.ReadLine();
        }

    }

Or...

    class Program
    {
        static void Main(string[] args){
            int? a = null;
            int b = a ?? 0;
            Console.WriteLine("Value of b is {0} ", b);
            Console.ReadLine();
        }
    }

We were able to refactor to two lines of code. In the code above it says, if a has been assigned a non-null value, then this value will be assigned to the int b. But, since the nullable type a has been assigned null, the value to the right of the operator ?? i.e. zero will be assigned to b instead.

The value of b - (0), is printed.

Next: Interfaces

Last updated