Sunday, November 22, 2009

The WTF Operator

Do you know what the ?? operator does ? I like to call it the WTF operator, as a lot of people have never seen it and can’t pick what it does immediately and because it’s not uncommon to see ?? after WTF (WTF??). It’s actually called the null-coalescing operator.

Basically it returns the value to the left of itself if that value is NOT null, else it returns the value to the right. For example, the following code sets ‘customer’ to either the m_Customer field or a new Customer object depending on whether or not m_Customer is null;

CustomerBase customer = m_Customer ?? new Customer();



Of course you can nest the ?? operator to build a form of coalesce statement;



private CustomerBase GetCustomer(CustomerBase customer)
{
return m_Customer ?? customer ?? new Customer();
}


Whether you should or not is another question, as readability and maintainability are more important than conciseness.



Hmmm, conciseness… is that really a word ? Spell check seems to think so.






Technorati Tags: ,,,,,

1 comment:

  1. Agree completely. Actually, the first thing that sprang to my mind when searching for ?? was 'WTF ?? C# operator' ... and voila, the answer is right here!

    ReplyDelete