Monday, July 10, 2006

Null Coalescing Operator in C# 2.0

Today while going through David Hayden's blog I found this "??" Null Coalescing Operator in C# 2.0.

This operator (null coalescing operator) is new in C# 2.0. The null coalescing operator provides inherent null-checking capabilities. The result of the expression is based on whether the first operand is null. If the first operand is not null, it is the result of the expression, otherwise, the result falls to the second operand. In other words, return the first value if not null, otherwise the second.

a ?? b is equivalent to a != null ? a : b.

To show an example of this operator. I created a new C# windows application wrote below code for Form_Load.

private void Form1_Load(object sender, EventArgs e)
{
int? a = null, b = 1;
int? x = a ?? b;
MessageBox.Show(x.ToString()); // x = 1
}

A couple of links on this are: Fritz Onion's blog and Oliver Sturm's blog .