| Start | ||||||
|---|---|---|---|---|---|---|
| Basic usage Using the Live Demo on .NET Fiddle (opens new window) This is logically equivalent to: or using the ternary operator (????? (opens new window) 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. Non-nullable Output: Type :System.Int32 Nullable
Multiple Coalescing Coalescing can also be done in chains: Output: Type :System.Int32 Null Conditional Chaining The null coalescing operator can be used in tandem with the null propagation operator (opens new window) to provide safer access to properties of objects. Output: Type :System.String |
||||||
| Null coalescing operator with method calls The null coalescing operator makes it easy to ensure that a method that may return Without the null coalescing operator: With the null coalescing operator: |
||||||
| 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. |
||||||
Lazy properties initialization with null coalescing operator The first time the property Thread safetyThis is not thread-safe way of implementing lazy properties. For thread-safe laziness, use the C# 6 Syntactic Sugar using expression bodiesNote 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 patternThis 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: Syntax
Parameters
RemarksThe 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. |
Read Article
https://develop.horje.com/learn/1434/reference