X

C# Null Coalescing Operator

dotnet C#

The ?? operator is called the null coalescing operator. It is used for providing a default value for Nullable types or reference types.

Example:


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

Taswar Bhatti:
Related Post