web analytics

Conditional Operator (?:) vs Null Coalescing Operator (??) in C#

Options

codeling 1595 - 6639
@2021-04-05 15:13:40

Conditional Operator (?:)

As you already know, the conditional operator (?:) in C# returns one of two values depending on the value of a Boolean expression. For example:

string employeeName = "Dave Gate";

Console.WriteLine(employeeName != null ? employeeName : "Employee name not specified.");

In the above example, if condition is true, employee name is outputted; if false, message "Employee name not specified." is outputted.

You can rewrite the above example using equivelent if-then statement, see the code below:

string employeeName = "Dave Gate";

if (employeeName != null)
{
   Console.WriteLine( employeeName);
}
else
{
   Console.WriteLine("Employee name not specified");
}

I am sure every C# programmer would like to use the conditional operator rather than the equivelent if-then statement, because much less keyboard inputs is needed and code is neater when using conditional operator.

@2021-04-05 15:16:19

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.

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com