Pranay Rana: Coalescing operator - ??

Friday, December 24, 2010

Coalescing operator - ??

Coalescing operator is new operator added in C#2.0. Coalescing operator is also known as ??.

How Coalescing operator works?
Note 
Here I am just going to show how coalescing operator replace ternary operator. i.e not comparing ternary operator with coalescing operator.
Ternary Operator
Syntax
Type variable = booleanCondition ? exp1 : exp2;

Ternary operator assign exp1 to variable if the booleanCondition return true or exp2 if booleanCondition return false.
Consider Case were I am coding with the nullable type using ternary opertor.

Example
Nullable<int> a = null;
Nullable<int> b = 10;
int c = a==null ? b.Value : a;

Coalescing operator
Coalescing operator work some what similar to ternary operator but it works only with the Nullable types only. so its sort hand operator to deal with Nullable types only.

Syntax
Type variable = nullalbeTypeVariable1.Value ?? nullableTypeVariable2.Value;

Operator its check value of nullalbeTypeVariable1 if its as real value rater tan null it assin value to variable else assign value of nullableTypeVariable2.

Example
Nullable<int> a = null;
Nullable<int> b = 10;
int c = a ?? b.Value;

Summary
Coalescing operator deals with Nullable type and its sort for long ternary operator expression.

No comments:

Post a Comment