C# Null-Coalescing Operator

The null-coalescing operator ?? in C# is used to define a fallback value when a variable is null.

Key Topics

Syntax

The syntax for the null-coalescing operator is:

variable ?? fallbackValue;

Example: Null-Coalescing Operator

string name = null;
string displayName = name ?? "Default Name";
Console.WriteLine(displayName);

Output:

Default Name

Code Explanation: Since the variable name is null, the operator returns the fallback value "Default Name".

Key Takeaways

  • The null-coalescing operator ?? returns the left-hand operand if it is not null, otherwise, it returns the right-hand operand.