DEV Community

Cover image for The null-coalescing operator in C# 8.0
Mauro Petrini 👨‍💻
Mauro Petrini 👨‍💻

Posted on • Edited on

3

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

class Program
{
static void Main(string[] args)
{
static int? GetNullAge() => null;
static int? GetAge() => 27;
int? age = GetNullAge();
//Old Way
//if (age == null)
//{
// age = GetAge();
//}
//C# 7
//age = age ?? GetAge();
//C# 8.0
age ??= GetAge();
Console.WriteLine(age);
Console.ReadLine();
}
}
view raw Program.cs hosted with ❤ by GitHub

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay