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 Null Coalescing operator as follows:

a ?? b

If a is a 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.

TIP: For the remaining operators, please refer to the C# Operators Introduction post available on our C# tutorial page.

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

TicketsAvailable = 0

The code without using the 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);
        }
    }
}
Null Coalescing Operator 1

Now let us initialize, TicketsonSale = 100, which 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 the 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 a nullable int type to a non-nullable int type and then storing it in a non-nullable int variable TicketsAvailable.

Now using the 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, 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);
        }
    }
}
TicketsAvailable= 100

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

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

TIP: The next step is to learn about the C# Arithmetic Operators and C# Relational Operators.

Categories C#