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

  1. int? x = null;  
  2. int y = x ?? 99;  
  3. Console.WriteLine("The Value of 'Y' is:" + y);  
  4. string message = "Operator Test";  
  5. string resultMessage = message ?? "Original message is null";  
  6. Console.WriteLine("The value of result message is:" + resultMessage);  
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 in the second example. We could check whether the message was null and return an alternate value and result message return "Operator test because 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.



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

  1. 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>" +   
  2. "<Name>Rakesh</Name>" + "<Address>BVN</Address>" + "</Node>" + "</Root>";   
  3.    
  4. XDocument xmlDoc = XDocument.Load(new StringReader(myXML));    
  5. var empData = (from emp in xmlDoc.Descendants("Node")    
  6.   
  7. select new    
  8. {    
  9.    Id = (int?)emp.Element("ID"),    
  10.    Name = (string)emp.Element("Name"),    
  11.    Address = (string)emp.Element("Address")    
  12. });    


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.
  1. var empData = (from emp in xmlDoc.Descendants("Node")  
  2. select new  
  3. {  
  4.       Id = (int?)emp.Element("ID")??0,  
  5.       Name = (string)emp.Element("Name"),  
  6.       Address = (string)emp.Element("Address")  
  7. });  


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

Up Next
    Ebook Download
    View all
    milton
    Read by 0 people
    Download Now!
    Learn
    View all