Introduction
In this blog, I am going to discuss ?? operator in C#.
?? Operator
?? is known as a null-coalescing operator. If the operand is not null, then it returns a left hand operand else it returns a right hand operand.
For example,
- Employee emp1 = null;
- Employee emp2 = emp1 ?? (emp1 = new Employee());
?? is a specific type of ternary operator. If we have to write the above code using ternary operator, then the following code needs to be written.
- Employee emp1 = null;
- Employee emp2 = (emp1 != null) ? emp1 : new Employee ();
Conclusion
If we have to check an object's null reference in ternary operator, then it can be achieved using ?? operator with minimal code.