The null-propagation operator, introduced in C# 6.0, eliminates the need for multiple null checks within a method call chain.
The null-propagation operator was introduced in C# 6.0.
It eliminates the need for multiple null checks within a method call chain, by returning null
when the object it's being called on is null
, instead of calling the target method (or accessing the target property) and throwing a NullReferenceException
.
string name = null;
int? nameLength = name?.Length; // stores null in nameLength
The benefit becomes more apparent when dealing with long call chains.
Imagine a series of simple classes defined as follows:
public class ClassRoom
{
public List<Student> Students { get; set; }
}
public class Student
{
public List<Subject> Subjects { get; set; }
}
public class Subject
{
public string Name { get; set; }
}
Safely accessing the length of a subject name, when only provided with a ClassRoom
, requires somewhat lengthy and repetitive code:
int? nameLength = null;
if (c != null
&& c.Students != null
&& c.Students.Count > 0
&& c.Students[0].Subjects != null
&& c.Students[0].Subjects.Count > 0
&& c.Students[0].Subjects[0].Name != null)
{
nameLength = c.Students[0].Subjects[0].Name.Length;
}
The same code, rewritten using the null-propagation operator:
int? nameLength = c?.Students?[0].Subjects?[0].Name?.Length;