Tuesday, September 7, 2010

Null-coalescing operator in C#

This is the first time I seriously took an opportunity to look at null-coalescing operator in C#. Introduced in C# 2.0, this is one cool operator that I have hardly put into practice. Well, until now but not anymore. :)

Null-coalescing operator is used to define a default value for nullable types as well as reference types. Let's look at an example.

loginName = loginName ?? "guest";
What we are doing here is using the null-coalescing operator to check whether "loginName" is null. If it is null, the default value "guest" is assigned to it. This could have been done otherwise using a if-else block:
if(loginName == null)
   loginName = "guest";
, or even using a ternary operator:
loginName = (loginName == null) ? "guest" : loginName;
But isn't the null-coalescing operator more sweeter version! In case of strings, I would advise you to use IsNullOrEmpty or IsNullOrWhitespace methods of string class. One way to make sure you get a trimmed login name, you could use a combination as above:
loginName = (string.IsNullOrWhiteSpace(loginName) ? null : loginName.Trim()) ?? "guest";
One more example can be when you need to know if a connection is initialized yet or not. And if not, initialize with the default connection string.
conn = conn ?? new SqlConnection(defaultConnectionString);
Lets look at one more example. Consider a method that sets an Employee status to active. The method also makes sure that if it is passed a reference to an employee not initialized yet, it creates a new active employee and returns it.
public Employee SetEmployeeActive(Employee emp)
    //if employee object is not initialized yet, initialize it
    emp = emp ?? (new Employee());
    emp.IsActive = true;

    return emp;
Happy null-coalescing!