How to use the null coalescing operator in C#
The null coalescing operator ?? in C# returns the left operand if it's not null, otherwise it returns the right operand. It's a concise way to provide default values for nullable types.
The null coalescing assignment operator ??= assigns the right operand to the left operand only if the left operand is null.
These operators help write cleaner code by eliminating verbose null checks and making default value patterns more readable.
C# Example Code
using System;
public class NullCoalescing
{
public static void Main(string[] args)
{
// Basic null coalescing operator ??
string? userName = null;
string displayName = userName ?? "Guest";
Console.WriteLine($"Display name: {displayName}"); // Guest
// With non-null value
string? actualUser = "Alice";
string greeting = actualUser ?? "Guest";
Console.WriteLine($"Greeting: Hello, {greeting}!"); // Hello, Alice!
// Chaining multiple ??
string? first = null;
string? second = null;
string? third = "Default";
string result = first ?? second ?? third ?? "Final fallback";
Console.WriteLine($"Result: {result}"); // Default
// Null coalescing assignment ??=
string? config = null;
config ??= "default-config"; // Assigns only if null
Console.WriteLine($"Config: {config}"); // default-config
config ??= "another-value"; // Does NOT assign (config is not null)
Console.WriteLine($"Config still: {config}"); // default-config
// Practical example: lazy initialization
string? cachedData = null;
cachedData ??= LoadExpensiveData();
Console.WriteLine($"Cached: {cachedData}");
}
static string LoadExpensiveData()
{
Console.WriteLine("Loading data...");
return "Expensive Data";
}
}