Powered by Blogger.

Saturday, February 22, 2014

Null Coalescing Operator in C#.Net

In this article we will discuss about C#.Net Null Coalescing operator. You can also check my previous posts on:

- List all Stored Procedure Created and Modified in Last N Days in SQL Server 2008

- How to implement FileUpload Control in Update Panel using asp.net?

- Difference between Dataset and Datareader asp.net

This is a binary operator which is helpful in case of Null values evaluation and is noted as ??

A ?? B

Here it means if A is not null then evaluate A else take the value of Y.


int? i = null;
int j = a.Value;

Here in the 2nd statement it will give an exception because we are trying to get the value which is null.

So to avoid the situation we can use Null Coalescing Operator

int? i = null;
int j = a ?? 0;

Here it will not give any exception rather it will take 0 and assign it to j.

If a is not null then it will evaluate a else it will take the value provided in Null Coalescing Operator which is 0 in this example.