Null Coalescing Operator (??) in C#

In this blog, I am going to share with you about Null Coalescing Operator (??) in C#.
 
Null Coalescing Operator (??)
  1. A syntax used to check null and assign a default value if null
  2. This operator can be used with Nullable types as well as reference types.
  3. This operator can be represented as x ?? y.
Here, x and y are the left and right operands. The left operand (x) can be nullable type while the right operand should have non-nullable value. If the value of x is null, then the syntax returns the value of y; else the value of x will be returned. This means that the value of left operand will be returned if its value is not null; else the value of right operand will be returned.

Why should we use Null Coalescing Operator (??)?
 
There are numerous of uses/advantages of Null Coalescing Operator,
 
It helps in preventing InvalidOperationException.
 
When we run the below program then 'a.Value' throw an InvalidOperationException exception as "An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll. Additional information: Nullable object must have a value."
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             int? a = null;  
  10.             int? b = a.Value;  
  11.   
  12.             Console.ReadKey();  
  13.   
  14.         }  
  15.     }  
  16. }  
This can be overcome by null coalescing operator as shown in below program. 'b' is assigned with default value 33 as 'a' is null.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             int? a = null;  
  10.             int? b = a ?? 33;  
  11.             Console.WriteLine("Value of a= " + a + " and b= " + b);  
  12.             Console.ReadKey();  
  13.   
  14.         }  
  15.     }  
  16. }  
Output
 
Value of a= and b= 33
 
It helps in defining a default value for a nullable item as we did in above program.(assigning a default value 33)
 
It removes many redundant "if-else" conditions and makes the code more organized and readable.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             int? a = null;  
  10.   
  11.             int? b;  
  12.             if (a.HasValue)  
  13.             {  
  14.                 b = a;  
  15.             }  
  16.             else  
  17.             {  
  18.                 b = 33;  
  19.             }  
  20.             Console.WriteLine("Value of a= " + a + " and b= " + b);  
  21.             Console.ReadKey();  
  22.   
  23.         }  
  24.     }  
  25. }  
The above code can be re-written using null coalescing as shown below,
  1. using System;  
  2.   
  3. namespace Tutpointorganized
  4.   class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         { 
  8.             int? a = null;  
  9.   
  10.             int? b = a ?? 33;  
  11.   
  12.             Console.WriteLine("Value of a= " + a + " and b= " + b);  
  13.             Console.ReadKey();  
  14.   
  15.         }  
  16.     }  
  17. }  
The program above is looking clean, organized and easily readable. It minimises the use of if-else conditions in one line. Also, the number of line of codes decrease. The output is same for both programs.
 
Output
 
Value of a= and b= 33
 
Null coalescing works for both reference-types and value-types.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // String is reference type  
  10.             string str1 = null;  
  11.             string str2 = "Hello";  
  12.             string str3 = "Buddy";  
  13.   
  14.             string str4 = str1 ?? str2;  
  15.             str3 = str4 ?? str2;  
  16.   
  17.             // Value type  
  18.             int? a = null;  
  19.             bool? c = null;  
  20.             Program p = new Program();  
  21.             bool? b = c ?? p.IsValue(11, 33);  
  22.   
  23.             Console.WriteLine("str3= " + str3 + " , str4= " + str4 + " b=" + b);  
  24.             Console.ReadKey();  
  25.   
  26.         }  
  27.         public Nullable<bool> IsValue(int? num1, int? num2)  
  28.         {  
  29.             try  
  30.             {  
  31.                 if (num1.HasValue && num2.HasValue)  
  32.                 {  
  33.                     return true;  
  34.                 }  
  35.                 else  
  36.                     return false;  
  37.   
  38.             }  
  39.             catch (Exception)  
  40.             {  
  41.                 return null;  
  42.             }  
  43.         }  
  44.     }  
  45.   
  46. }  
In the above program, we have shown how to use both reference type as well as value type. We can also use a method as an operand on null coalescing syntax.

In line bool? b = c ?? p.IsValue(11, 33);

value of c is null so the value of right operand will be evaluated. As both the parameter's value is not null, IsValue(11,13) will return true and true will be assigned to b.
 
This operator can be nested, which looks like a chain.
 
Null coalescing can be nested to make a chain like structure as shown below in the program. This also reduces the if-else condition statements and make the code more readable and easy to understand.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             int? num1 = null;  
  10.             int? num2 = null;  
  11.             int? num3 = 3;  
  12.             int? num4 = num1 ?? num2 ?? num3;  
  13.   
  14.             Console.WriteLine("Value of num4 = " + num4);  
  15.             Console.ReadKey();  
  16.   
  17.         }  
  18.     }  
  19.   
  20. }  
Output
 
Value of num4 = 3
 
Conclusion
 
Null coalescing should be incorporated inside code to minimise the line of code and to standardized the code. This does not make much improvement on the performance but it optimise the code. This makes the code easy to understand.
 
Thank you. Please feel free to ask any question or make a suggestion.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now