?? (null-coalescing) Operator In C#

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,
  1. Employee emp1 = null;  
  2. 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.
  1. Employee emp1 = null;  
  2. 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.

Next Recommended Reading Null Coalescing Operator (??) in C#