Coalescing operator in C#
The Coalescing operator is short cut instead of IF condition.
Working
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.Value ? b.Value : a;
Summary
Coalescing operator deals with Nullable type and its sort for long ternary operator expression.
Have a nice day... 'N happy Coding :)
No comments:
Post a Comment