Null Coalescing (??) Operator in C#

Introduction

The ?? operator is also known as the null-coalescing operator. It returns the left side operand if the operand is not null else it returns the right side operand.

Example

int? x = null;
int y = x ?? 99;
Console.WriteLine("The Value of 'Y' is: " + y);
string message = "Operator Test";
string resultMessage = message ?? "Original message is null";
Console.WriteLine("The value of result message is: " + resultMessage);

Output

Output

In the preceding example, we have an integer variable "x" that is a nullable type and has a null value so in the result variable "Y" the return value is 99. The same is true in the second example. We could check whether the message was null and return an alternate value resulting in a message return " Operator test because the message variable has value.

A nullable type can represent a value that can be undefined or from the type's domain. We can use the ?? operator to return an appropriate value when the left operand has a nullable type. If we try to assign a nullable value type to a non-nullable value type without using the ?? operator, we will get a compile-time error and if we forcefully cast it, an InvalidOperationException exception will be thrown.

InvalidOperationException

The ?? operator works for both reference types and value types. In the preceding example, y is an integer (value type) and returnMessage is a string type (reference type).

The following are the advantages of the Null-Coalescing Operator (??) operator.

  • It is used to define a default value for a nullable item (for both value types and reference types).
  • It prevents the runtime InvalidOperationException exception.
  • It helps us to remove many redundant "if" conditions.
  • It works for both reference types and value types.
  • The code becomes well-organized and readable.

Use Null- Coalescing Operator (??) operator with LINQ

The ?? operator can be useful in scenarios where we deal with raw XML and the XML shapes are irregular and/or missing elements/attributes.

Let us then consider the following example. Here we have XML that contains employee data. We could write the following LINQ to XML query for an anonymous type object with Id, Name, and Address properties. It returns a null value of the Id column because one node of data is missing the "ID” sub-element.

string myXML = "<Root> " +
                "<Node> " +
                "<ID>1</ID>" +
                "<Name>Tejas</Name>" +
                "<Address>BVN</Address>" +
                "</Node>" +
                "<Node> " +
                "<Name>Jignesh</Name>" +
                "<Address>BVN</Address>" +
                "</Node>" +
                "<Node> " +
                "<ID>3</ID>" +
                "<Name>Rakesh</Name>" +
                "<Address>BVN</Address>" +
                "</Node>" +
                "</Root>";

XDocument xmlDoc = XDocument.Load(new StringReader(myXML));
var empData = (from emp in xmlDoc.Descendants("Node")
               select new
               {
                   Id = (int?)emp.Element("ID"),
                   Name = (string)emp.Element("Name"),
                   Address = (string)emp.Element("Address")
               });

Enumerable

The ?? operator is useful when we need to show a value other than null. In the preceding example, we just use this operator as shown in the following code.

var empData = (from emp in xmlDoc.Descendants("Node")
               select new
               {
                   Id = (int?)emp.Element("ID") ?? 0,
                   Name = (string)emp.Element("Name"),
                   Address = (string)emp.Element("Address")
               });

Enumerable

Summary

The null-coalescing (??) operator is very simple and it can be very helpful in null-checking scenarios.


Similar Articles