Wednesday, April 29, 2009

I don't know what it's called, but I like it

I've recently started using JetBrains' Resharper. Today I was reviewing the code inspection rules and came across a few that had to do with using an operator with which I was unfamiliar. So I took a moment to learn about the ?? operator (link) which must have come out with the .NET 2.0 framework because it has to do with nullable types.

What it does is kind of like the old IsNull method from VB (you remember VB don't you?). Here's an example in two lines:

int? x = null;

int y = (null != x) ? x : -1;

The first line declares a nullable int variable named x which is assigned null.
The second line declares a non-nullable int variable named y. Because it's not nullable we've got to ensure a null value isn't being assigned (otherwise we'll raise an exception). To do this we're using the ternary operator. What the ?? operator does is allow us to write the second line like this:

int y = x ?? -1;

So if x is null y is set to -1. Nice, right? Especially if you replace x and y with more meaningful variable names, such as this:

int? someMeaningfulName = null;

int whatYouReallyWant = someMeaningfulName ?? -1;

Or, more common in my current job, getting values from a web form or querystring:

int desiredFormId = 0;

if (null != Request.Form["Activate_FormId"]) {
desiredFormId = Request.Form["Activate_FormId"];

can become:

int desiredFormId = Request.Form["Activate_FormId"] ?? 0;

Now if I could just figure out how to pronouce this operator I can tell people about it.