C# LanguageNull-Coalescing Operator


  • var result = possibleNullObject ?? defaultValue;


possibleNullObjectThe value to test for null value. If non null, this value is returned. Must be a nullable type.
defaultValueThe value returned if possibleNullObject is null. Must be the same type as possibleNullObject.


The null coalescing operator itself is two consecutive question mark characters: ??

It is a shorthand for the conditional expression:

possibleNullObject != null ? possibleNullObject : defaultValue

The left-side operand (object being tested) must be a nullable value type or reference type, or a compile error will occur.

The ?? operator works for both reference types and value types.