TOC

The community is working on translating this tutorial into Romanian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Operatori:

The NULL coalescing operator

The ?? operator is also called the "null-coalescing operator" because it allows you to check for a NULL value and assign a fallback value in one line of code. This might seem trivial to do without this operator, but consider the following example:

string userSuppliedName = null; 

if (userSuppliedName == null)
    Console.WriteLine("Hello, Anonymous!");
else
    Console.WriteLine("Hello," + userSuppliedName);

You should think of the variable userSuppliedName as something that comes from the user, e.g. from a dialog or a data file - something that could result in the value being NULL. We must deal with this by checking the value before using it, in this case for displaying the name to the user.

In the above example, we use the classical if-else approach, but with the null-coalescing operator, we can do it much shorter, in a single line:

Console.WriteLine("Hello, " + (userSuppliedName ?? "Anonymous")); 

In a single statement, we ask the interpreter to use the userSuppliedName variable if it has a value – if not, we supply a fallback value, in this case the name "Anonymous". Short and simple!

Summary

As with all "syntactical sugar", like the null-coalescing operator, it's always a compromise between keeping the code short and readable. Some find that these operators make it harder to read and navigate the code, while others love how short and simple it is. In the end, it's all up to you!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!