Happy toast

Getting Query String Parameters Safely and Concisely in C#

  1. c#

Getting String Values

Getting the string value of a parameter in your query string is trivial:

string city = Request.QueryString["city"];

The only caveat is if the parameter doesn’t exist in the query string, in which case you’ll get a null value. This can be perfectly fine, and even useful, as long as your code knows how to handle it. But if you’re afraid of null reference exceptions and would rather get empty strings in place of nulls, then you can use the ?? (coalesce) operator:

string city = Request.QueryString["city"] ?? "";

The coalesce operator returns the expression on its left if that expression is not null, otherwise it’ll return the expression on its right, which is an empty string in this case.

Getting Non-String Values

So getting string values out of your query string is easy. After all, it is a query string. But what if you need the value as another type, like an integer? The cheap approach is this:

int page = Convert.ToInt32(Request.QueryString["page"]); // don't do this

But that assumes our parameter will actually be a numeric string. And you should never make assumptions about what’s in your query string. It’s far too easy to hack, mistype, misencode, or otherwise pollute the query string. If the value of page turns out to be “potato”, then we’ve just created a FormatException.

So what to do? Use TryParse() (documentation here). With some deft coding, we can write a full solution for safely getting a query string parameter with one line of code:

int page = int.TryParse(Request.QueryString["page"], out page) ? page : 1;

Alright, let’s dissect this. TryParse() takes in 2 parameters: the value to cast, and the variable to put the casted value into. TryParse() returns a boolean indicating success. So if TryParse() is successful, it’ll put a valid integer into the page variable, return true, and then the ?: (ternary) operator will just set page to itself, preserving the value that TryParse() put into it. If TryParse() fails, the ternary operator causes page to be set to 1 (or whatever default value you wish to use).

Additional Notes

  • Don’t forget to do any additional validation. My example allows the page variable to be negative, which is valid for an integer, but probably not what I want.
  • When TryParse() fails, it sets the C# default value for that type into the variable. For an int, this is 0. I use the ternary operator to change this to 1, but if the C# default is what you want, then you can forgo that part altogether.
  • My example uses an int, but you can also use TryParse() with other types, such as DateTime and Boolean.

And there you have it. Getting and casting query string parameters, safely and with fallback, with one line of code.

Thank you!