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.

What is a Null-Conditional operator?

Before C# 6

string name = null;   
int length = name.Length;  

It will throw the following error.

Programcs

In C# 6.0

using static System.Console;    
namespace BNarayan.NullConditionalOperator    
{    
    class Program    
    {    
        static void Main(string[] args)    
        {    
            string userName = "Banketeshvar Narayan";    
            userName = null;    
            if ((userName?.Length??0)>20)    
            {    
                WriteLine("UserName can not be more than 20 charcter long.");    
            }    
            else    
            {                    
                WriteLine("UserName length is: {0}", userName?.Length??0);    
            }     
        }    
    }    
}  

Output

Output is

If I comment on the line userName = null;

string userName = "Banketeshvar Narayan";  
//userName = null;    
if ((userName ? .Length ? ? 0) > 20)  
{  
    WriteLine("UserName can not be more than 20 charcter long.");  
}  
else  
{  
    WriteLine("UserName length is: {0}", userName ? .Length ? ? 0);  
}  

Output

Output

I have tested the output for some statements in the 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.


Similar Articles