Null Coalescing Operator (??)
Since C# 2.0, there is new operator called null coalescing operator (??) is available to provide inherent null-checking capabilities. It returns the left-hand operand if it is not null, or else it returns the right operand. For example, the equivelent statement using null coalescing operator (??) for the previous code is:
string employeeName = "Dave Gate";
Console.WriteLine(employeeName ?? "Employee name not specified");
The result of the expression is based on whether the first operand is null. If the first operand is not null, it is the result of the expression, otherwise, the result falls to the second operand. In other words, return the first value if not null, otherwise the second.
Another good example of using null coalescing operator is
//FindEmployee(int id) returns the employee haveing the same id,
//otherwise, returns null
Employee emp = FindEmployee(id) ?? new Employee(id);
The above statement calls the LoadEmployee method with employee id, if an employee is found, then it is assigned to emp variable, otherwise, the a new object is created.
Let's try to use the conditional operator to rewrite the above code. You may rewrite it as the code blow:
Employee emp = (FindEmployee(id) == null) ? FindEmployee(id) : new Employee(id);
But obviously, there is a potential performance issue because the the method FindEmployee get called twice with the same id. So let's continue working on the rewrite:
Employee emp = FindEmployee(id);
if (emp == null)
{
emp = new Employee(id);
}
The above code should be equivelent to the code using null coalescing operator, but i would definitely like to use null coalescing operator instead of conditional operator or if-then statements.