DEV Community

Nick
Nick

Posted on

Null Coalescing (??) Operator in C#

The C# Null Coalescing Operator (??) is a versatile operator that simplifies the handling of null values in C# code. It provides a concise way to specify a default value when a nullable variable is null, allowing you to write more concise and readable code.

To understand the Null Coalescing Operator, let's start with a simple scenario. Consider a variable called "name" that can either hold a string value or be null. If "name" is null, we want to assign a default value of "Anonymous" to it. Traditionally, we would use an if-else statement to achieve this:

string name = GetNameFromSomeSource(); // Assume this can return null

if (name == null)
{
    name = "Anonymous";
}
Enter fullscreen mode Exit fullscreen mode

With the Null Coalescing Operator (??), we can achieve the same result in a more concise way:

string name = GetNameFromSomeSource() ?? "Anonymous";
Enter fullscreen mode Exit fullscreen mode

In the above code, the "?? " operator performs a null check on the left-hand side variable (in this case, "name"). If the left-hand side is null, the operator returns the right-hand side value ("Anonymous" in this case) and assigns it to the left-hand side variable.

The Null Coalescing Operator can be used with any nullable type, including reference types and nullable value types. This means it can handle null values for strings, integers, bools, and other types.

Let's take another example where we want to assign a default value to an integer variable (age) if it is null:

int? age = GetAgeFromSomeSource(); // Assume this can return null

int defaultAge = 18; // Default age to be set if age is null
int actualAge = age ?? defaultAge;
Enter fullscreen mode Exit fullscreen mode

In this case, if the "age" variable is null, the Null Coalescing Operator assigns the value of "defaultAge" to "actualAge". Otherwise, it assigns the value of "age" itself.

In addition to assigning a default value, the Null Coalescing Operator can also be used to return a default value directly without assigning it to a variable. For example:

string favoriteColor = GetFavoriteColorFromSomeSource(); // Assume this can return null

string color = favoriteColor ?? "Blue";
Console.WriteLine(color); // Output: Blue
Enter fullscreen mode Exit fullscreen mode

In the above code, if "favoriteColor" is null, the Null Coalescing Operator returns the default value ("Blue") directly without assigning it to a variable.

Overall, the C# Null Coalescing Operator (??) is a handy tool for simplifying null checks and providing default values in C# code. It helps to write more concise and readable code by reducing the number of if-else statements and adding clarity to null value handling.

Top comments (0)