C# Double Question mark Operator (null-coalescing operator)

In C#, the Double Question Mark (??) operator is introduced in C# 7.x version. The operator has 2 operands and it returns the left operand if the left operand if it is not null, otherwise, returns the right operand.

     String language = "German";
     Console.WriteLine(language ?? "English");

In above code, since the left operand (i.e. language) is not null, the output is “German”.

Consider below Code:

     String language = null;
     Console.WriteLine(language ?? "English");

Here, the output is “English”.

Use of Double Question mark/null-coalescing operator

The null-coalescing operator helps in a much better code readability. It is just for the replacement of below “null check and then initialize” code:

        void getUserLanguage(User user)
        {
            if(user == null)
            {
                user = new User();
            }

            //code to get language
        }

is relpaced with

        void getUserLanguage(User user)
        {
            user = user ?? new User();

            //code to get language
        }

Updates in null-coalescing operator (question mark with equals operator)

Along with and after C# 8.0 version, the ?= operator is introduced, which assigns the value of right operand to left operand if left operand is null. Example of ?= operator:

getUserLanguage(user ??= new User());

A detailed documentation for this operator can be found on the Microsoft documentation site here.

Please let us know about your suggestions/questions in the comment box.

Leave a Comment

Your email address will not be published.