DEV Community

Cover image for The null-coalescing operator in C# 8.0
Mauro Petrini πŸ‘¨β€πŸ’»
Mauro Petrini πŸ‘¨β€πŸ’»

Posted on • Edited on

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

Top comments (1)

Collapse
 
peledzohar profile image
Zohar Peled • Edited

Nitpicking: The null coalescing operator (??) was around in c# 6 as well, and if memory serves, perhaps even also in c# 5. The null-coalescing assignment operator (??=) is new, though.