The Null Conditional Operator
Microsoft has released Visual Studio 2015 release candidate. We can assume the RTM version will arrive soon. Visual Studio 2015 is shipped with C# 6. C# 6.0 ships with lots of new features that helps developers improve the way they write code. One of the new feature added to C# 6 is the Null Conditional Operator (?).
What is Null Conditional Operator?
It is tricky to write a single line definition to null conditional operator. For the purpose of this article let me define Null-Conditional operator as follows.
“The null conditional operator prevents the execution of a method if the caller object is null.”
Syntax
Consider the following diagram that demonstrates a simple example of null conditional operator.
Whether you are novice or experienced developer you must be familiar with null reference exceptions. You must be tired of writing null checking code to make sure your application handles null references correctly. The null-conditional operator is going to save you from writing lots of null checking code. In this article I am going to explain the usage of null-conditional operator with the help of an example.
Consider the following classes
public class Student
{
public int id { get; set; }
public string name { get; set; }
public City city { get; set; }
}
public class City
{
public string name { get; set; }
public string zip { get; set; }
public Country country { get; set; }
}
public class Country
{
public string name { get; set; }
public string shortName { get; set; }
}
The classes are self-explanatory. The student class contains a city object and city contains a country object. I created an aspx page and placed certain label controls to display the student information. The page looks like below in the Visual Studio design surface.
Now let us consider the below code.
Student s = new Student();
s.id = 1;
s.name = "Sample Student";
lblStudentName.Text = s.name;
lblStudentID.Text = s.id.ToString();
lblCity.Text = s.city.name;
lblCountry.Text = s.city.country.name;
It is creating a student object and then displays its value. Since we didn’t assign city and country objects, while we run the project we will get the famous NullReferenceExcception.
So to avoid this, prior to C# 6.0, developers used to write the following code
if (s.city != null)
{
lblCity.Text = s.city.name;
}
The introduction of Null-Conditional operator in C# 6.0, makes this null checking simple. Now with the new Null-Conditional operator the above null checking code can be written as below.
lblCity.Text = s.city?.name;
The null conditional operator can be nested (chained). See the following example.
lblCountry.Text = s.city?.country?.name;
See the output of this page after we use null conditional operator
When you use null conditional operator, the expression may return null, so you need to make sure, you are using nullable datatypes while assigning values from null-conditional operator returns.
int id = s?.id;
The above statement will result in compile time error. You need to use nullable types with null-conditional operator. The following code will compile with out errors.
int? id = s?.id;
Usage with null coalesce operator
Sometimes you need to assign a default value to the expression you are evaluating. In your example, let us consider a situation, when a student’s country is not specified, assign it to “US”. This is a common scenario, you must have default values as per business rules. To achieve this, you can use null conditional operator along with null coalesce (??) operator.
E.g.
String countryCode = s?.city?.country?.shortName ?? "US";
int studentId = s?.id ?? 0;
The null-conditional operator eases the process of null checking. The null-conditional operator works with your custom objects, collections and delegates. The way the operator is designed to use will help the developers to adapt this easily and make the null checking a practice while you are writing code.