Checking for a QueryString value does not require a nested if for the null check

November 24, 2009

You no doubt often find yourself gathering QueryString values, and writing code dependent upon the values found.

You might write:

if (Request.QueryString["foo"] == 1)
 {
     // Do something
 }

Fine, but this will fail if ‘foo’ is not a valid entry found in the QueryString. You’ll get a null reference exception.

So how ahout this:

if (Request.QueryString["foo"] != null)
 {
     if (Request.QueryString["foo"] == 1)
     {
         // Do something
     }
 }

Yup, that’ll work, but its not exactly very elegant code!

Heres another way…

if (context.Request.QueryString["foo"] != null && context.Request.QueryString["foo"] == 1)
 {
     // Do something
 }

The key to this is the fact that we use ‘&&’ (Double ampersand) instead of a single ‘&’ for the comparison operator. The double & operator means the second (right hand side) test is only evaluated if the first (left hand side) test evaluates to true, so our null check happens first, if this is Ok the check for the value we are looking for happens. Assuming this is a match, the code inside our if block will run.

On the flipside of this, using a single ‘&’ means both tests are evaludated – If either or both result in false, the result is – False, otherwise, the result is true.

There is another option, which kind of negates the need for my demo of the double ‘&’ operator, and to be honest this is the best way

  • Declare your object at the level you need (e.g. Class, Method)
  • Initialise your object at the earliest opportunity, at the same point carrying out the null check, and probably substituting with value, depending on the logic of your application. You may also want to introduce some logic and security here by checking the value is within and expected ranges and of the expected type
  • Use the object, knowing it already has a sensible value
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: