Null Propagation Operator in C# 6.0

Introduction

In the field of computer science Microsoft has achieved new targets every day and makes new things for users. In these days Microsoft has introduced a new version of Visual Studio. The new version of Visual Studio is named Visual Studio 2015 Preview. Microsoft also introduced the new version of C#, C# 6.0. In this new version of C# Microsoft has added new features. Using these features this language will be stronger and more powerful and easy to use. Some features are String Interpolation, nameof operator, #pragma, null propagation operator, Expression bodied members, using static members, Auto-property initializers, Await in catch/finally, Exception filters and many more. As we know C# 6.0 in not yet complete so it will be premature to say that the features are finalized. There are no changes done from Microsoft to make C# 6.0 better, so working on it is a running state.

Null Reference Exception

So here is an explaination of the Null propagation operator in C# 6.0 that is a very useful operator in C# 6.0. It is also known as the Null conditional operator. The main purpose of the null propagation operator is to check the null values because most programmers forget to check out the null values during coding. Sometimes when programmers did not check for a null in the coding they get the exception
"System.NullReferenceException" also known as the Object reference not set to an instance of an object error. The main cause of this exception is that the programmer tried to access a method or member that is not present in the code or maybe is null so the compiler sends a null reference exception.

So first here we see an example of how a Null Reference Exception can exist in our code.

Code

  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main()  
  5.     {  
  6.         string str = null//here we declare the string as null  
  7.         if (str.Length == 0) // by this line the error will accured  
  8.         {  
  9.             Console.WriteLine(str); // due to exception compiler never goes on this line  
  10.         }  
  11.         Console.Read();  
  12.     }  
  13. }  
When we run this code it generates an exception known as a null reference exception just as in the following image.

Output




Now I will tell you how to remove this exception. First I make the code proper to remove this error. That means we provide a value for the string and then run it. I think then it will work properly. Let us see it.

There are two ways, one is to first pass a value for the String.

Code
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main()  
  5.     {  
  6.         string str = "rizwan ali mansoori";   
  7.         if (str.Length != 0)  
  8.         {  
  9.             Console.WriteLine("Now we provide the value for string and it is not null");  
  10.             Console.WriteLine("so out put is"  + str);   
  11.              
  12.         }  
  13.         Console.Read();  
  14.     }  
  15. }  
Output



The second way is to use try and catch blocks to handle an exception. Now see in the following example how to handle an exception using try and catch blocks.

Code
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main()  
  5.     {  
  6.         try  
  7.         {  
  8.             string str = null//here we declare the string as null  
  9.             if (str.Length == 0)// by this line the error will accured  
  10.             {  
  11.             }  
  12.          }  
  13.         catch (Exception ex)  
  14.         {  
  15.             Console.WriteLine("please provide te some value for the string");   
  16.         }  
  17.         Console.Read();  
  18.     }  
  19. }  
Output


This is the overall information about the Null Reference Exception, what is it, how it can exist, how to handle it in our code and what the reasons are for it. The end user never wants to see the abnormal termination of his code. He always wants a specific message or warning when he gets errors so it is necessary for every programmer to please check for the null value of every member that we use in our code.

Null Propagation Operator(?) in C# 6.0

As we said above, C# 6.0 introduced the null propagation operator for checking for null values in code. The null propagation operator is denoted by "?". The basic advantage of using the null propagation operator is to reduce the code we write to check the null condition in our code. Using this operator we can have less code than the previous code. Using the null propagation operator we can easily manage the null reference exception.

Before we write the code something like this:

  1. Console.WriteLine(a.age == null ? 10001 : a.age.no1);  
But now we write it in a minimized way like this.
  1. Console.WriteLine(a.age?.no1 ?? 10001 );  

Here I provide an example of the Null propagation operator.

Example

  1. using System;  
  2. namespace ConsoleApplication5  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             var a = new first  
  9.             {  
  10.                 number = 1234  
  11.             };  
  12.             Console.WriteLine(a.age.no1);  
  13.   
  14.             Console.Read();  
  15.         }  
  16.     }  
  17.     class first  
  18.     {  
  19.         public int number { getset; }  
  20.         public second age { getset; }  
  21.     }  
  22.   
  23.     class second  
  24.     {  
  25.         public int no1 { getset; }  
  26.         public int no2 { getset; }  
  27.     }  
  28. }  
It provides the null reference exception like the output.

Output



Now we handle this exception by the old method.

Code of the old method
  1. using System;  
  2. namespace ConsoleApplication5  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             var a = new first  
  9.             {  
  10.                 number = 1234  
  11.             };  
  12.             Console.WriteLine(a.age == null ? 10001 : a.age.no1);//old method  
  13.   
  14.             Console.Read();  
  15.         }  
  16.     }  
  17.     class first  
  18.     {  
  19.         public int number { getset; }  
  20.         public second age { getset; }  
  21.     }  
  22.   
  23.     class second  
  24.     {  
  25.         public int no1 { getset; }  
  26.         public int no2 { getset; }  
  27.     }  
  28. }  
Output



Now finally we remove this exception using the null propagation operator and reduce the code. If we do not specify null then we check for null only by the "?" operator.

Code  of new method
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace ConsoleApplication5  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             var a = new first  
  14.             {  
  15.                 number = 1234  
  16.             };  
  17.             Console.WriteLine(a.age?.no1 ?? 10001); //new code  
  18.   
  19.             Console.Read();  
  20.         }  
  21.     }  
  22.     class first  
  23.     {  
  24.         public int number { getset; }  
  25.         public second age { getset; }  
  26.     }  
  27.   
  28.     class second  
  29.     {  
  30.         public int no1 { getset; }  
  31.         public int no2 { getset; }  
  32.     }  
  33. }  
Output



Summary

C# 6.0 has many new features in it. One of them is the null propagation operator. It has the property that if we make a reference variable in our code and want to check its value for null or not null before invoking the object so using the null propagation operator we can check it and remove the null exception error. It also increases the reliability of code and reduces the lines of code. That makes the code cleaner and easier.