Introduction
On November 12, 2014, the day of the Visual Studio Connect() event, Microsoft announced Visual Studio 2015 Preview with many new and exciting features for developers for testing purposes. Microsoft announced the new version of C#, C# 6.0 that came with many improvements and new features. One of the newly introduced features of C# 6.0 is the Null Propagation Operator.
Don't forget to read my previous posts on this series: "A new feature of C# 6.0".
System.NullReferenceException: Object reference not set to an instance of an object.
System.NullReferenceException is a very common exception that indicates we are trying to access member fields, or function types, on an object reference that points to null or is not present in the code. We receives this exception when we have not checked for a null in our code. This exception is also known as Object reference not set to an instance of an object. Let's see how we get a NullReferenceException and how to handle it.
- using System;
- public class Person
- {
- public int Age { get; set; }
- }
- public class Book
- {
- public Person Author { get; set; }
- }
- public class execution
- {
- public static void Main(string[] args)
- {
- Book b1 = new Book();
- int authorAge = b1.Author.Age;
- }
- }
When we run this code snippet, an unhandled exception of type "System.NullReferenceException" occurs in our application.
Now we can handle this exception using try {} and catch {} blocks.
- using System;
- public class Person
- { public int Age { get; set; } }
- public class Book
- { public Person Author { get; set; } }
- public class execution
- {
- public static void Main(string[] args)
- {
- Book b1 = new Book();
- try { int authorAge = b1.Author.Age; }
- catch (NullReferenceException e) { Console.WriteLine(e.Message); }
- Console.ReadKey();
- }
- }
Output
Since we are using the new keyword that only creates a new instance of the class Book, but does not create a new instance of the class Person, the Author property is still null.
All programmers want their program to terminate in abnormal conditions. So to avoid this, checking for a null value of every member is useful. C# 6.0 has introduced the Null-Propagation Operator (?.) that enables developers to check for the null value in an object reference chain.
What is Null Propagation Operator
C# 6.0 introduced many new features in Visual Studio 2015 Preview. Let's have a look at one of its new features, the Null Propagation Operator. In earlier versions of the C# language, we always had to write an if condition for a null check before using an object or its property. Now C# 6.0 has introduced the Null-Propagation Operator (?.) that enables developers to check for the null value with in an object reference chain. The null-propagation operator (?.) will return null if anything in the object reference chain is null. We need a better way of handling null exceptions where null propagation exists. The null propagation operator can now be used like nullable types by putting a question mark (?) after the instance before calling the property. We don't need to write additional if statements to check for the null values.
Example 1
In earlier versions of the C# language, you always had to check for nulls explicitly before using an object or its property, as shown below.
- if (Employee.Name == null)
- {
- Console.WriteLine("No Employee name provided");
- }
The same can be converted into a one-liner using the Conditional Access Operator in C# 6.
- Console.WriteLine(Employee?.Name ?? "No Employee name provided");
Example 2
Suppose we have a class called Student that has another property studentdetails of type Details class. Now we can have the following code snippet to print the Address.
- if (student != null && student.studentdetails != null)
- {
- Console.WriteLine(student.studentdetails.Address);
- }
- else
- {
- Console.WriteLine("No Address");
- }
As we can see, to avoid the null-reference exception, we have checked the null for student and student.studentdetails since they can have a null reference as object. So, the preceding code snippet can be re-written using the null propagation operator (?.) as follows:
- Console.WriteLine(student?.studentdetails?.Address ?? "No Address");
Both code snippets will provide us the address of the student.
What I think is, it's a really nice feature because instead of checking each and individual objects, using the null propagation operator (?.) we can check the entire chain of references together and whenever there is a null value in the entire chain of reference, it will return null.
Demo application using Visual Studio 2013
- using System;
- namespace CSharpFeatures
- {
- class NullPropagation
- {
- static void Main()
- {
- Student student1 = new Student();
- student1.Name = "Siddharth";
- student1.rollno = 12;
- student1.studentdetails = new Details() { Address = "Lakshmi Nagar New Delhi India", Email = "[email protected]" };
-
- Student student2 = new Student();
- student2.Name = "Aditya";
- student2.rollno = 05;
- student2.studentdetails = new Details() { Address = null, Email = null };
-
- Console.WriteLine("Student 1:\n");
- if (student1.Name == null) Console.WriteLine("No Name Provided");
- else Console.WriteLine(student1.Name);
- if (student1.studentdetails.Address == null) Console.WriteLine(" No Address Provided");
- else Console.WriteLine(student1.studentdetails.Address);
- if (student1.studentdetails.Email == null) Console.WriteLine("No Email Address Provided");
- else Console.WriteLine(student1.studentdetails.Email);
- Console.WriteLine("\nStudent 2:\n");
- if (student2.Name == null) Console.WriteLine("No Name Provided");
- else Console.WriteLine(student2.Name);
- if (student2.studentdetails.Address == null) Console.WriteLine("No Address Provided");
- else Console.WriteLine(student2.studentdetails.Address);
- if (student2.studentdetails.Email == null) Console.WriteLine("No Email Address Provided");
- else Console.WriteLine(student2.studentdetails.Email);
- Console.ReadLine();
- }
- }
- class Student
- {
- public string Name { get; set; }
- public int rollno { get; set; }
- public Details studentdetails { get; set; }
- }
- class Details
- {
- public string Address { get; set; }
- public string Email { get; set; }
- }
- }
Output
Demo application using Visual Studio 2015 Preview
- using System;
- using System.Console;
- namespace CSharpFeatures
- {
- class NullPropagation
- {
- static void Main()
- {
- Student student1 = new Student();
- student1.Name = "Siddharth";
- student1.rollno = 12;
- student1.studentdetails = new Details()
- { Address = "Lakshmi Nagar New Delhi India", Email = "[email protected]" };
-
- Student student2 = new Student();
- student2.Name = "Aditya";
- student2.rollno = 05;
- student2.studentdetails = new Details()
- { Address = null, Email = null };
- WriteLine("Student 1:\n");
- WriteLine(student1?.Name ?? "No Name");
- WriteLine(student1?.studentdetails?.Address ?? "No Address");
- WriteLine(student1?.studentdetails?.Email ?? "No Email provided");
- WriteLine("\nStudent 2:\n");
- WriteLine(student2?.Name ?? "No Name");
- WriteLine(student2?.studentdetails?.Address ?? "No Address");
- WriteLine(student2?.studentdetails?.Email ?? "No Email provided");
- ReadLine();
- }
- }
- class Student
- {
- public string Name { get; set; }
- public int rollno { get; set; }
- public Details studentdetails { get; set; }
- }
- class Details
- {
- public string Address { get; set; }
- public string Email { get; set; }
- }
- }
Output
Summary
In this article we learned about the new feature of C# 6.0, the null propagation operator that will definitely improve the developer's productivity by reducing the number of lines in a code and also by reducing the numbers of bugs in the code and will keep the code clean. Don't forget to read my other articles on the series "A new feature of C# 6.0". Share your opinion about this feature and how you will use it in your project. Your comments are most welcome. Happy Coding!