This is my personal blog. The views expressed on these pages are mine alone and not those of my employer.

Tuesday, 5 October 2010

C# Conditional Operator ( ?: ) and Null-Coalescing Operator ( ?? )

After spending a couple of years in the software industry its becoming more and more apparent  to me just how little I actually know.  It seems that every time I learn something new, something groundbreaking, a new world of possibilities opens up.  One such event occurred today.

A little known operator (??) can do away with bulky if...else statements and tidy up the source code.  Suppose you want to assign something to a variable, but only want to do so if that value isn't null?  Its something I know I do pretty much every day, usually with code such as:

   1:  if (x != null)
   2:       {
   3:         y = x;
   4:       }
   5:       else
   6:       {
   7:         y = "";
   8:       }

This can be completely replaced with:

   1:  y = x ?? "";

How cool is that?

In addition a single (?) can be used as a boolean conditional operator, so instead of testing for null it can test for any boolean to be true.  For example:

   1:  y = x != null ? x : "";

This article was written because of inspiration from both here and here

I'm going to be using these quite a bit I think.

No comments:

Post a Comment