C# Null Coalescing operator

C# Null Coalescing operator ?? is a binary operator, and it can be used with both nullable types and reference types.

The syntax is of the C# Null Coalescing operator as follows:

a ?? b

If a is non-null value, then evaluate to a, otherwise b

Let us see an example to understand the usage of the Null Coalescing operator.

C# Null Coalescing operator Example

TicketsAvailable is a non-nullable int variable, whereas TicketsonSale is a nullable int variable holding the value of Null. In the if condition, we are checking whether TicketsonSale is null.

Here, in this case, we have assigned TicketsonSale to null, so obviously the result will be

TicketsAvailable = 0

C# code without using Null Coalescing

using System;

namespace CSharp_Tutorial
{
    class Without_NullCoalesce
    {
        static void Main()
        {
            int TicketsAvailable;
            int? TicketsonSale = null;

            if (TicketsonSale == null)
            {
                TicketsAvailable = 0;
            }
            else
            {
                TicketsAvailable = (int)TicketsonSale;
            }

            Console.WriteLine("TicketsAvailable = {0}", TicketsAvailable);
        }
    }
}

OUTPUT

C# Null Coalescing Operator 1

Now let us initialize, TicketsonSale = 100, it means the else part will be executed.  

The reason why we have typecast TicketsonSale to Non-Nullable int variable is,

TicketsonSale is a nullable int variable, and we are trying to store the value of nullable int variable into a non-nullable int variable, i.e., TicketsAvailable.

It gives an error. So it is a process of Converting the result of nullable int type to non-nullable int type and then storing in a non-nullable int variable TicketsAvailable. 

Now using Null Coalescing operator(??), we can reduce the if statement part to a single line of code, i.e., 

TicketsAvailable = TicketsonSale ?? 0;

This single line of the C# code is saying that if ‘TicketsonSale’ is null return 0. And if it is not null, then return the value in the TicketsAvailable, Which, in this case, returns 100.

C# code using Null Coalescing Operator

using System;

namespace CSharp_Tutorial
{
    class Null_Coalesing
    {
        static void Main()
        {
            int TicketsAvailable;
            int? TicketsonSale = 100;

            //Using Coalesce operator ??
            TicketsAvailable = TicketsonSale ?? 0;


            Console.WriteLine("TicketsAvailable  = {0}", TicketsAvailable);
        }
    }
}

OUTPUT

C# Null Coalescing Operator 2

TicketsAvailable = 100 because TicketsonSale = 100 i.e., not null

If TicketsonSale = Null then the TicketsAvailable would be equal to 0.