Monday, April 25, 2005
Null Coalescing Operator in C# 2.0
In C# 2.0 a new null coalescing operator, ??, is provided. a ?? b is equivalent to a != null ? a : b. The null coalescing operator works on both reference types and nullable types in C# 2.0.
Nullable Type Example:
Reference Type Example:
Nullable Type Example:
int? a = null, b = 1;
int x = a ?? b; // x = 1
a = 2;
x = a ?? b; // x = 2
Reference Type Example:
object a = null, b = "foo";
object x = a ?? b; // x.ToString() = "foo"
a = "bar";
x = a ?? b; // x.ToString() = "bar"




