NULL Conditional Operator In C# 6.0

Sometimes developers get the following exception: “object reference not set to an instance of an object”. Whenever we got such type of exception our mouth fell open but in C# 6 we can handle it easily using NULL Conditional Operator. So we can handle “System.NullReferenceException” using this operator. I am going to explain it with a very simple example where I am handling NullReferenceException for string datatype.

Null-Conditional operator (?.)

Before C# 6,

  1. string name = null;   
  2. int length = name.Length;  
It will throw the following error,

Length

In C# 6.0
  1. using static System.Console;    
  2.     
  3. namespace BNarayan.NullConditionalOperator    
  4. {    
  5.     class Program    
  6.     {    
  7.         static void Main(string[] args)    
  8.         {    
  9.             string userName = "Banketeshvar Narayan";    
  10.             userName = null;    
  11.             if ((userName?.Length??0)>20)    
  12.             {    
  13.                 WriteLine("UserName can not be more than 20 charcter long.");    
  14.             }    
  15.             else    
  16.             {                    
  17.                 WriteLine("UserName length is: {0}", userName?.Length??0);    
  18.             }     
  19.         }    
  20.     }    
  21. }  
Output
 
Output is

If I comment the line userName = null; 
  1. string userName = "Banketeshvar Narayan";  
  2. //userName = null;    
  3. if ((userName ? .Length ? ? 0) > 20)  
  4. {  
  5.     WriteLine("UserName can not be more than 20 charcter long.");  
  6. }  
  7. else  
  8. {  
  9.     WriteLine("UserName length is: {0}", userName ? .Length ? ? 0);  
  10. }  
Output

Output

I have tested the output for some statement in Immediate window which is as follows:

tested the output

I have explained it in more details.

Must visit the above link it has more explanation.

X

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

Start Learning Now