Null-conditional operator
The worst thing that a developer can do is not check for null in code. This means that there is no reference to an object, in other words, there is a null. Reference-type variables have a default value of null. Value types, on the other hand, cannot be null. In C# 2, developers were introduced to the nullable type. To effectively make sure that objects are not null, developers usually write sometimes elaborate if
statements to check whether objects are null or not. C# 6.0 made this process very easy with the introduction of the null-conditional operator.
It is expressed by writing ?.
and is called the question-dot operator. The question is written after the instance, right before calling the property via the dot. An easy way to think of the null-conditional operator is to remember that if the left-hand side of the operator is null, the whole expression is null. If the left-hand side is not null, the property is invoked and becomes the result of the operation. To really see the power of the null-conditional operator is to see it in action.
Getting ready
We will create another class that will illustrate the use of the null-conditional operator. The method will call a Student
class to return a count of students in the resulting list. We will check to see whether the Student
class is valid before returning the student count.
How to do it…
- Create another class called
Recipe2NullConditionalOperator
beneath the last class you wrote in the Creating your Visual Studio project recipe:public static class Recipe2NullConditionalOperator { }
- Add a method called
GetStudents
to the class and add the following code to it:public static int GetStudents() { List<Student> students = new List<Student>(); Student st = new Student(); st.FirstName = "Dirk"; st.LastName = "Strauss"; st.JobTitle = ""; st.Age = 19; st.StudentNumber = "20323742"; students.Add(st); st.FirstName = "Bob"; st.LastName = "Healey"; st.JobTitle = "Lab Assistant"; st.Age = 21; st.StudentNumber = "21457896"; students.Add(st); return students?.Count() ?? 0; }
- Next, add a third class to your code called
Student
with the following properties:public class Student { public string StudentNumber { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public string JobTitle { get; set; } }
- Our
Student
class will be the object we will call from ourGetStudents
method. In theProgram.cs
file, add the following code:int StudentCount = Chapter1.Recipe2NullConditionalOperator.GetStudents(); if (StudentCount >= 1) Console.WriteLine($"There {(StudentCount > 1 ? "are " : "is ")}{StudentCount} student{(StudentCount > 1 ? "s" : "")} in the list."); else Console.WriteLine($"There were {StudentCount} students contained in the list."); Console.Read();
- Running the console application will result in the application telling us that there are two students contained in the list. This is expected, because we added two
Student
objects to ourList<Student>
class: - To see the null-conditional operator in action, modify the code in your
GetStudents
method to set thestudents
variable to null. Your code should look like this:public static int GetStudents() { List<Student> students = new List<Student>(); Student st = new Student(); st.FirstName = "Dirk"; st.LastName = "Strauss"; st.JobTitle = ""; st.Age = 19; st.StudentNumber = "20323742"; students.Add(st); st.FirstName = "Bob"; st.LastName = "Healey"; st.JobTitle = "Lab Assistant"; st.Age = 21; st.StudentNumber = "21457896"; students.Add(st); students = null; return students?.Count() ?? 0; }
- Run the console application again, and see how the output has changed:
How it works…
Consider the code we used in the return
statement:
return students?.Count() ?? 0;
We told the compiler to check whether the List<Student>
class' variable students
is null. We did this by adding ?
after the students
object. If the students
object is not null, we use the dot operator, and the Count()
property becomes the result of the statement.
If the students
object however is null, then we return zero. This way of checking for null makes all that if(students != null)
code unnecessary. The null check sort of fades into the background and makes it much easier to express and read null checks (not to mention less code).
If we had to change the return
statement to a regular Count()
method without the null-conditional operator, we would see an ArgumentNullException was unhandled
error:
return students.Count();
Calling Count()
on the students
object without using the null-conditional operator breaks the code. The null-conditional operator is an exciting addition to the C# language because it makes writing code to check for null a lot easier. Less code is better code.