Understanding the Null-Coalescing Assignment Operator (??=)

Understanding the Null-Coalescing Assignment Operator (??=)
Understanding the Null-Coalescing Assignment Operator (??=)

The ??= operator is called the null-coalescing assignment operator in C#.
It was introduced in C# 8.0 and makes code much cleaner and shorter.

In simple terms :
If the variable is null, assign a value. If it is not null, do nothing.
That's the core idea.

How did we do it before?

Before the ??= operator, we had to manually check for null like this:

if (legsTipActive == null)
{
    legsTipActive = new List<bool>();
}

This approach works, but you needed three lines for a simple operation.

How is it different now?

Now with the ??= operator, you can do the same thing in just one line:

legsTipActive ??= new List<bool>();

Short, clean, and easy to read.

Practical Example

Let's look at a real-world example. If you have a static list and you want to initialize it only when needed, you can write:

public static List<bool> legsTipActive;

void Awake()
{
    legsTipActive ??= new List<bool>();
}
  • If legsTipActive is already created, nothing happens.
  • If it is null, a new List<bool> is created.

Simple and safe.

When is it useful?

The ??= operator is especially useful when:

  • Initializing singleton instances
  • Lazy-loading data structures
  • Ensuring collections are ready before using them
  • Setting default values without overwriting existing ones

Example applied to Singleton Pattern

private static GameData _instance;

public static GameData Instance
{
    get
    {
        _instance ??= FindObjectOfType<GameData>();
        return _instance;
    }
}

With this, GameData is found and assigned only when it is actually needed.

Summary

  • The ??= operator checks if a variable is null and assigns a value only if needed.
  • It replaces 3-4 lines of null-check + assignment code with just one line.
  • It is especially useful when initializing lists, dictionaries, singleton instances, and more.

From now on, if you see code like this:

if (something == null)
{
    something = new Something();
}

change it to just one line:

something ??= new Something();

and enjoy much cleaner code.

Popular posts from this blog

Understanding Arrays as Reference Types in C#

Setting Up a Basic Follow Camera with Cinemachine 3.x

Understanding and Using ? (nullable) in C#