Information Technology Reference
In-Depth Information
Using Operators and the Null Coalescing Operator
The standard arithmetic and comparison operators have been updated to handle nullable
types. There is also a new operator called the null coalescing operator , which allows you to
return a value to an expression, in case a nullable type variable is null .
The null coalescing operator consists of two contiguous question marks and has two
operands:
￿
The first operand is a variable of a nullable type.
￿
The second is a non-nullable value of the same underlying type.
If, at run time, the first operand evaluates as null , the second operand is returned as the
result of the operation.
￿
Null coalescing operator
int? MyI4 = null;
Console.WriteLine("MyI4: {0}", MyI4 ?? -1);
MyI4 = 10;
Console.WriteLine("MyI4: {0}", MyI4 ?? -1);
This code produces the following output:
MyI4: -1
MyI4: 10
The equality comparison operators, == and != , have an interesting characteristic you need
to be aware of. If you compare two values of the same nullable type, and both are null , the
equality comparison operators consider them equal. For example, in the following code the
two nullable int s are set to null . The equality comparison operator will declare them equal.
int? I1 = null, I2 = null; // Both are null.
if (I1 == I2) // Operator returns true.
Console.WriteLine("Equal");
Search WWH ::




Custom Search