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!