Introduction
In this article, we’ll explore null-conditional operators in C#. These operators were introduced in C# 6.0 and provide a concise way to handle null scenarios, simplify null checks, and avoid NullReferenceExceptions. Let’s dive into the details!
1. Null-Conditional operator (?.)
The null-conditional operator (?.) is also known as the safe navigation operator. It allows you to access members of an object only if the object is non-null. Here’s how it works:
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public Person Spouse { get; set; }
}
// Without null-conditional operator
Person person = GetPerson();
int? age = null;
if (person != null)
{
age = person.Age;
}
// Using null-conditional operator
Person person = GetPerson();
var age = person?.Age; // 'age' will be of type 'int?', even if 'person' is not null
// Chaining the operator
// Will be null if either 'person' or 'person.Spouse' are null
int? spouseAge = person?.Spouse?.Age;
// Combining with the null-coalescing operator to provide a default value
// 'spouseDisplayName' will be "N/A" if 'person', 'Spouse', or 'Name' is null
var spouseDisplayName = person?.Spouse?.Name ?? "N/A";
2. Null-Conditional index (?[])
Similar to the ?. operator, the null-conditional index operator (?[]) checks for null values when indexing into a collection that may be null:
string item = collection?[index];
// Is syntactic sugar for:
// string item = null;
// if (collection != null)
// {
// item = collection[index];
// }
3. Avoiding NullReferenceExceptions
The null-conditional operator helps prevent NullReferenceExceptions. For example:
var person = new Person { Address = null };
var city = person.Address.City; // Throws a NullReferenceException
var nullableCity = person.Address?.City; // Returns the value of null
// Chaining multiple null-conditional operators
var person = new Person { Address = new Address { State = new State { Country = null } } };
// This will always return a value of at least "null" instead of throwing an exception
var countryName = person?.Address?.State?.Country?.Name;
4. Null-conditional operator with extension methods
Extension methods can work on null references, but you can use ?. to null-check anyway:
public class Person
{
public string Name { get; set; }
}
public static class PersonExtensions
{
public static int GetNameLength(this Person person)
{
return person == null ? -1 : person.Name.Length;
}
}
// Normally, the method will be triggered for null references and return -1:
Person person = null;
int nameLength = person.GetNameLength(); // Returns -1
Summary
Null-conditional operators ?. and?[] enhance code readability and safety by preventing null reference exceptions and reducing the need for explicit null checks. They are especially useful when dealing with complex object hierarchies or collections where any intermediate value might be null.