The ?? operator is called the null coalescing operator. It is used for providing a default value for Nullable types or reference types.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
int? age = null; //what ?? implies is possiblyNullValue ?? valueIfNull int myAge = x ?? 100; //if x is not null then assign x else 100 string? person = null; string? localDefault = null; string globalDefault = "abc"; string anybody = person ?? localDefault ?? globalDefault; //chaining ?? //lazy loading/populating private SomeObj _lazyField = null; public SomeObj MyProperty { get { return _lazyField ?? (_lazyField = new SomeObj()); } } |
One of the disadvantage of ?? is it can create code that is not that readable.
e.g a ?? b ?? c ?? d ?? e
Leave A Comment