C# Null-Conditional Operator
In one of his videos, Gerald Versluis encountered a question about the question mark (?) in his sample code. This led him to create a detailed video explaining the null-conditional operator in C#. If you've ever wondered what ?.
or ?[ ]
does in C#, Gerald's video is a great resource to understand it clearly. Let's go through his explanation step by step.
Quick Explanation Through Docs Page
Gerald begins by referring to the official Microsoft documentation on member access operators and expressions. He highlights the section about the null-conditional operator, introduced in C# 6. At the time of recording, C# 9 was the latest version, with C# 10 on the horizon.
Gerald explains that when you use a?.x
or a?[index]
, if a
is null, the entire expression evaluates to null instead of throwing a NullReferenceException. Otherwise, it retrieves the value normally.
While documentation is helpful, Gerald prefers hands-on examples, so he moves to an interactive coding environment.
Example Through try.dot.net
To demonstrate, Gerald switches to try.dot.net, an interactive C# environment. He mentions that this tool runs on Blazor, allowing users to execute C# code directly in a browser.
He briefly shows the default Fibonacci sequence example, which is preloaded in try.dot.net, and then clears it to start a new example focusing on the null-conditional operator.
Null-Conditional Operators Explained
Gerald creates a simple Person class with the following properties:
public class Person
{
// The Name property of the Person
public string Name { get; set; }
// A reference to another Person object representing the partner
public Person Partner { get; set; }
// An array representing the Person's hobbies
public string[] Hobbies { get; set; }
}
public class Person
{
// The Name property of the Person
public string Name { get; set; }
// A reference to another Person object representing the partner
public Person Partner { get; set; }
// An array representing the Person's hobbies
public string[] Hobbies { get; set; }
}
He initializes a Person
object as null:
// Initialize a Person object as null
Person person = null;
// Attempting to access a property of a null object will throw a NullReferenceException
Console.WriteLine(person.Name);
// Initialize a Person object as null
Person person = null;
// Attempting to access a property of a null object will throw a NullReferenceException
Console.WriteLine(person.Name);
Running this code throws a NullReferenceException because person
is null. To prevent this, developers typically add a null check before accessing properties:
// Check if the person object is not null before accessing its properties
if (person != null)
{
Console.WriteLine(person.Name);
}
// Check if the person object is not null before accessing its properties
if (person != null)
{
Console.WriteLine(person.Name);
}
While this works, it introduces extra lines of code. Gerald explains how the null-conditional operator simplifies this:
// Using the null-conditional operator to safely access the Name property
Console.WriteLine(person?.Name);
// Using the null-conditional operator to safely access the Name property
Console.WriteLine(person?.Name);
Now, if person
is null, the expression simply returns null instead of crashing.
Null-Conditional Operator on Properties
Gerald expands the example by setting up a Person
object:
// Create a new Person object
Person person = new Person { Name = "Gerald" };
// Access the Name property safely
Console.WriteLine(person?.Name);
// Create a new Person object
Person person = new Person { Name = "Gerald" };
// Access the Name property safely
Console.WriteLine(person?.Name);
Since person
is not null, it correctly prints "Gerald".
Next, he shows a nested example:
// Safely access the Name property of the Partner object
Console.WriteLine(person?.Partner?.Name);
// Safely access the Name property of the Partner object
Console.WriteLine(person?.Partner?.Name);
If person.Partner
is null, the whole expression evaluates to null instead of throwing an exception. This avoids unnecessary if conditions.
Chaining Null-Conditional Operators
Gerald explains that null-conditional operators can be chained, making code cleaner when dealing with deeply nested objects. Instead of writing multiple null checks, you can use:
// Chain null-conditional operators to safely access nested objects
Console.WriteLine(person?.Partner?.Name);
// Chain null-conditional operators to safely access nested objects
Console.WriteLine(person?.Partner?.Name);
If person
or person.Partner
is null, the result will be null, preventing runtime errors.
Null-Conditional Operators on Arrays
Gerald extends the discussion to arrays and collections. He adds a Hobbies array to the Person class and shows how to access elements safely:
// Safely access the first element of the Hobbies array
Console.WriteLine(person?.Hobbies?[0]);
// Safely access the first element of the Hobbies array
Console.WriteLine(person?.Hobbies?[0]);
Here, if person
or Hobbies
is null, the expression evaluates to null instead of causing an exception.
Conclusion
Gerald's video provides an in-depth look at the null-conditional operator in C#. By using ?.
and ?[ ]
, developers can write cleaner, safer code that avoids NullReferenceException. Whether dealing with properties, nested objects, or arrays, the null-conditional operator makes code more concise and readable.
For a full demonstration, be sure to check out Gerald Versluis’ video where he explains everything with practical examples!