The C# Null Coalescing Operator

Introduction

A the ?? operator is a binary operator that is used to simplify checking for null values.

If the left operand is not null, it returns the left operand, otherwise it returns the right operand.

For example:

This means that:

Is equivalent to:

And is even shorter than:

The ?? operator is right-associative, which means that it is evaluated from right to left. This means that:

is evaluated as:

Rules

  • Arguments can be reference types or nullable types.
  • If both arguments are constant, the result is not considered to be a constant.
  • Both arguments must be of the same type.

Uses

Assigning a Non-Nullable Type from a Nullable Type

int result;
int a? = null;
result = a ?? 1; // Assigns 1 to result.

Lazily Instantiated Properties

Avoiding Double Evaluation
Chaining

References

Leave a Reply

Your email address will not be published. Required fields are marked *