Null Coalescing Operators ?? / ??=
The ?? (null-coalescing operator) returns a fallback value when the operand is null, ??= assigns a value only when the variable is null, and ?. (null-conditional operator) accesses a member with a built-in null check.
Syntax
// Returns the right-hand value if the left-hand side is null. var result = variable ?? defaultValue; // Assigns the right-hand value only when the variable is null. variable ??= defaultValue; // Accesses a member with a null check (returns null if the object is null). var value = obj?.Property; var value = obj?.Method(); // Combines ?. and ??. var value = obj?.Property ?? defaultValue;
Operator Reference
| Operator | Description |
|---|---|
| a ?? b | Returns a if it is not null; otherwise returns b. |
| a ??= b | Assigns b to a only if a is null. Does nothing if a is not null. |
| a?.b | Returns a.b if a is not null. Returns null if a is null (no exception thrown). |
| a?[i] | Returns a[i] if a is not null. |
| a?.b?.c | Chains multiple null checks together. |
Sample Code
using System;
// Use ?? to set a default value.
string name = null;
string displayName = name ?? "Guest";
Console.WriteLine(displayName); // Guest
string alias = "Tanaka";
Console.WriteLine(alias ?? "Guest"); // Tanaka
// Use ??= to assign only when the variable is null.
string cache = null;
cache ??= "initial value";
Console.WriteLine(cache); // initial value
cache ??= "not overwritten";
Console.WriteLine(cache); // initial value (unchanged because it is not null)
// Use ?. for null-safe member access.
string text = null;
int? length = text?.Length; // No exception even when text is null.
Console.WriteLine(length); // (empty — outputs null)
string realText = "Hello";
Console.WriteLine(realText?.Length); // 5
Console.WriteLine(realText?.ToUpper()); // HELLO
// Combine ?. and ??.
string input = null;
int len = input?.Length ?? 0;
Console.WriteLine(len); // 0
// Example with a class.
class User { public string Address { get; set; } }
User user = null;
string address = user?.Address ?? "No address registered";
Console.WriteLine(address); // No address registered
Notes
Combining ?? and ?. significantly reduces the number of null-checking if statements. Verbose code like if (obj != null) return obj.Value; else return default; can be written in a single line.
To make value types (such as int or bool) nullable, see Nullable<T> / Nullable Types. For type checking and casting, see is / as / Pattern Matching.
If you find any errors or copyright issues, please contact us.