The null-coalescing operator in C# 8.0

mpetrinidev

Mauro Petrini 👨‍💻

Posted on September 23, 2019

The null-coalescing operator in C# 8.0

Welcome! Spanish articles on LinkedIn. You can follow me on Twitter for news.


What is null-coalescing?

According to ms docs, the null-coalescing operator ?? returns the value of its left-hand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator does not evaluate its right-hand operand if the left-hand operand evaluates to non-null.

Through a Youtube video, I'll show how to use the null coalescing operator in C# 8.0 and the evolution of this:

  • Old way
  • With C# 7
  • Finally with C# 8.0

Example

We have a variable called age with a null value

    static int? GetNullAge() => null;
    static int? GetAge() => 27;

    int? age = GetNullAge();

Old way

We need to check if the value is null and then assign the value

    if (age == null)
    {
        age = GetAge();
    }

C# 7

We use the null coalescing operator

    age = age ?? GetAge();

C# 8.0

We use the compound assignment operator

    age ??= GetAge();

For more information:

Youtube video

Github GIST

💖 💪 🙅 🚩
mpetrinidev
Mauro Petrini 👨‍💻

Posted on September 23, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related