- var result = possibleNullObject ?? defaultValue;
|The value to test for null value. If non null, this value is returned. Must be a nullable type.|
|The value returned if |
The null coalescing operator itself is two consecutive question mark characters:
It is a shorthand for the conditional expression:
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.
null-coalescing operator (??) allows you to specify a default value for a nullable type if the left-hand operand is
This is logically equivalent to:
or using the ternary operator (?:) operator:
Lazy properties initialization with null coalescing operator
The first time the property
.FooBars is accessed the
_fooBars variable will evaluate as
null, thus falling through to the assignment statement assigns and evaluates to the resulting value.
This is not thread-safe way of implementing lazy properties. For thread-safe laziness, use the
Lazy<T> class built into the .NET Framework.
C# 6 Syntactic Sugar using expression bodies
Note that since C# 6, this syntax can be simplified using expression body for the property:
Subsequent accesses to the property will yield the value stored in the
Example in the MVVM pattern
This is often used when implementing commands in the MVVM pattern. Instead of initializing the commands eagerly with the construction of a viewmodel, commands are lazily initialized using this pattern as follows:
Null coalescing operator with method calls
The null coalescing operator makes it easy to ensure that a method that may return
null will fall back to a default value.
Without the null coalescing operator:
With the null coalescing operator:
Null fall-through and chaining
The left-hand operand must be nullable, while the right-hand operand may or may not be. The result will be typed accordingly.
output will be of type
int? and equal to
Coalescing can also be done in chains:
Null Conditional Chaining
The null coalescing operator can be used in tandem with the null propagation operator to provide safer access to properties of objects.
value :Default Value
Use existing or create new
A common usage scenario that this feature really helps with is when you are looking for an object in a collection and need to create a new one if it does not already exist.