C# Language Null-Coalescing Operator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • var result = possibleNullObject ?? defaultValue;

Parameters

ParameterDetails
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.

Remarks

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.



Got any C# Language Question?