C# Null-Coalescing Operator (??)

C# has an operator called Null-Coalescing Operator(??), this operator takes two operands. If left hand side operand is not null then it returns left hand side operand else it returns right hand side operands. It is very effective to assign default value to a variable.

This variable can be used with reference type as well as nullable value types. A sample code for the use of this operator is written below:



            Int32? i = null;

            int j = i ?? 1; // This is similar to
                                //int j = i.HasValue ? i.Value : 1;
                                //Since i is null in this case so that value of j will be 1.

No comments:

Post a Comment