Thinking way too long about the subtitle RSS 2.0
 Sunday, April 01, 2007

I recently became aware of the "??" operator in C#. I guess it doesn't have a real name like the ternary operator that I've long been a fan of using. I'll call it the WTF operator until I learn a better (more popular) name. Let's take a look at the "What The #$@#%@#" operator in action:

public int PageTabId
{
   get { return Convert.ToInt32(Request.QueryString["PageTabId"] ?? "-1"); }
}

Per the MSDN reference, the WTF operator inspects the value on the left side of the "??". If it's null, the value on the right is returned. If its not null, the value on the left is returned. Its a lot like IsNull in T-SQL. The code example above is just a simple helper property for an ASP.Net page. The property looks for a querystring value. If its there, the value is cast as an integer and returned to the caller. If its not in the querystring, the default integer value of -1 is returned.

I've been using the ternary operator for a while. Here's the same property as above, but uses the ternary operator instead. Its more verbose than WTF, but still one line of code.

public int PageTabId
{
   get 
   { 
      return Request.QueryString["PageTabId"] != null 
         ? Convert.ToInt32( Request.QueryString["PageTabId"] ) : -1; 
   }
}

I love writing WTF all over my code!

Sunday, April 01, 2007 3:29:02 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
asp.net | learning
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Andrew Hay
Sign In
All Content © 2010, Andrew Hay
DasBlog theme 'Business' created by Christoph De Baene (delarou)