This is a mirror of official site:

C# Null Coalescing Operator and its Uses

| Tuesday, August 23, 2011
The C# Null Coalescing Operator (??)  is a binary operator that simplifies checking for null values. It can be used with both nullable types and reference types. It is represented as x ?? y which means if x is non-null, evaluate to x; otherwise, y. In the syntax x ?? y

    x is the first operand which is a variable of a nullable type.
    y is the second operand which has a non-nullable value of the same type.

While executing code, if x evaluates to null, y is returned as the value. Also remember that the null coalescing operator (??) is right-associative which means it is evaluated from right to left. So if you have an expression of the form x ?? y ?? z, this expression is evaluated as x?? (y?? z).

Note: Other right-associative operators are assignment operators, lambda and conditional operators.

Now with an overview of the C# Null Coalescing operator, let us see how to use the Null coalescing operators in practical scenarios.

Scenario 1 – Assign a Nullable type to Non-Nullable Type

Consider the following piece of code where we are assigning a nullable type to a non-nullable type.


C# Nullable Type

In the code above, if the nullable type (in our case ‘a’) has a null value and the null value is assigned to a non-nullable type (in our case ‘b’), an exception of type InvalidOperationException is thrown, as shown below:


Read more: net curry .com
QR: ShowArticle.aspx?ID=745

Posted via email from Jasper-net