a blog for those who code

Monday, 28 July 2014

Null Coalescing operator (??) in C#

In this post we will show you what is Null Coalescing Operator in C#. Null Coalescing Operator is a binary operator used to check null values. It returns the left-hand operand if the operand is not null otherwise it will return right hand operand.

Null Coalescing operator simplifies checking for null values.

Syntax is, a ?? b

where a is an operand of nullable type and b is an operand of non-nullable type.

Suppose you do something like,

int? a = null;
int b = a.Value; //It will throw "Nullable object must have a value" error

To resolve this error you can use Null Coalescing operator (??)

int? a = null;
int b = a ?? 0;

So, in the above code if a is not-null b will be assigned with that otherwise it will be assigned with 0.

Advanced use of Null Coalescing operator (??)

a. string value = value1 ?? value2 ?? value3 ?? value4;

We can use Null Coalescing operator to chain values like the above code, where "value" will have the first not-null value. Note that in string Empty is not considered as Null so suppose if value1 is "" (Empty String) then your value will be assigned with "".

b. List<int> a = b ?? new List<int>;

Suppose you want to assign an integer list to another integer list and if you want to check if it is null or not then you can do something like the above statement.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment