Iron Academy Logo
Learn C#

Understanding the C# Null Coalescing Operator

Gerald Versluis
12m 43s

The null coalescing operator (??) in C# allows developers to simplify null-checking logic, reducing code verbosity and improving readability. Instead of writing lengthy if-else conditions, this operator provides a concise way to assign fallback values when encountering null. In this article, we will explore the null coalescing operator in detail by following along with Gerald Versluis’ video, "Understanding C# Null Coalescing Operator (?? and ??=)." We will break down the key sections of the video and analyze how Gerald demonstrates this useful C# feature.

Introduction

At the start of the video, Gerald introduces the null coalescing operator as a powerful feature in C# that significantly reduces the number of lines of code needed for null checking. He emphasizes that this operator simplifies conditional checks and makes the code more readable. To illustrate its benefits, Gerald walks through a sample application where he implements and explains various use cases of the null coalescing operator.

Sample App Outline

Gerald begins by setting up a simple console application. He mentions that, in previous videos, he has used the try.dot.net website for demonstrations, but due to version limitations (supporting only C# 7), he switches to Visual Studio for Mac. He assures that the examples will work on Visual Studio for Windows as well.

To prepare the demonstration, Gerald creates a basic Person class with a single Name property:

public class Person {
    public string Name { get; set; }
}
public class Person {
    public string Name { get; set; }
}
TODO
$vbLabelText   $csharpLabel

He then initializes an instance of this class to showcase how the null coalescing operator functions in real-world scenarios.

Replace Null Check with Null-Coalescing Operator (??)

Gerald now demonstrates how the null coalescing operator (??) can be used to simplify null-checking logic. He assigns null to the Name property and then uses ?? to provide a fallback value:

var name = person.Name ?? "Gerald";
var name = person.Name ?? "Gerald";
TODO
$vbLabelText   $csharpLabel

Gerald explains that prior to this operator, developers would use an if statement:

string name;
if (person.Name == null)
{
    name = "Gerald";
}
else
{
    name = person.Name;
}
string name;
if (person.Name == null)
{
    name = "Gerald";
}
else
{
    name = person.Name;
}
TODO
$vbLabelText   $csharpLabel

By using ??, this logic is reduced to a single line. When person.Name is null, "Gerald" is assigned; otherwise, person.Name retains its value. He runs the program and confirms that the output is correct.

Null-Coalescing to Throw Exceptions

Next, Gerald explores another use case: throwing exceptions using the null coalescing operator. Instead of providing a fallback value, he demonstrates how to throw an exception when encountering null:

var name = person.Name ?? throw new ArgumentNullException(nameof(person.Name), "Name cannot be null");
var name = person.Name ?? throw new ArgumentNullException(nameof(person.Name), "Name cannot be null");
TODO
$vbLabelText   $csharpLabel

Gerald highlights that this is particularly useful when working with method parameters or properties where null should not be allowed. He explains that this feature was introduced in C# 7 or 8, depending on the project settings. Running the code with a null value for person.Name results in an ArgumentNullException, effectively preventing unintended null references.

Null Coalescing Compound Assignment (??=)

Gerald moves on to discuss the null coalescing compound assignment (??=) operator, which provides an even more streamlined way to assign default values. Instead of writing:

if (person.Name == null)
{
    person.Name = "Gerald";
}
if (person.Name == null)
{
    person.Name = "Gerald";
}
TODO
$vbLabelText   $csharpLabel

He simplifies this with:

person.Name ??= "Gerald";
person.Name ??= "Gerald";
TODO
$vbLabelText   $csharpLabel

Gerald explains that ??= assigns the specified value only if the left-hand operand is null. If person.Name already has a value, it remains unchanged. This operator is particularly useful for initializing fields or ensuring that variables never remain null.

Combining with the Null Conditional Operator

In the final section, Gerald demonstrates how the null coalescing operator can be combined with the null conditional operator (?.). The null conditional operator allows safe access to properties without causing a NullReferenceException. He provides an example:

var length = person?.Name?.Length ?? 0;
var length = person?.Name?.Length ?? 0;
TODO
$vbLabelText   $csharpLabel

Gerald explains that this ensures that if person or Name is null, the result defaults to 0 instead of throwing an exception. This combination is useful when working with nullable reference types or complex object hierarchies.

Conclusion

Throughout the video, Gerald Versluis effectively explains the power of the null coalescing operator (??) and the null coalescing compound assignment (??=). He demonstrates how these operators can replace traditional null checks, making the code more concise and readable. By leveraging these features, developers can write cleaner and more efficient C# applications.

If you’re interested in seeing these concepts in action, check out Gerald Versluis’ full video on "Understanding C# Null Coalescing Operator (?? and ??=)."

Hero Worlddot related to Understanding the C# Null Coalescing Operator
Hero Affiliate related to Understanding the C# Null Coalescing Operator

Earn More by Sharing What You Love

Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!