Query String tips with C# 2.0

by Peter Tyrrell Thursday, November 02, 2006 3:11 PM

I switched from VB.NET to C# a few months ago because of the JetBrains Resharper Visual Studio add-in.

C# has been a joy for the most part. I am occasionally stumped because it is stricter than VB.NET, but working through such challenges makes me understand the C# language and .NET framework better.

Ted and I, and I guess other asp.net developers, work with query strings a LOT. I discovered a couple of new methods in .NET 2.0 that are helping me out with the HttpRequest.QueryString collection.

String.IsNullOrEmpty(string): bool

A typical scenario is to init a string, pass it a query string value, and then check to see that the string has a value. I'm always trying to remember whether a non-existent query string key returns null, or an empty string. Or if the key is there but has no value, is that null or an empty string? With String.IsNullOrEmpty, I don't have to think:

string CheckId = Request.QueryString["ID"];

if (string.IsNullOrEmpty(CheckId) == false)


    //do stuff


Int32.TryParse(string, out Int32): bool

In the code example above, I want an ID value, which I need to be a integer. I want to test that it is a number before proceeding, and I also want to actually convert it to an integer. In the past I would use VB.NET's IsNumeric, and then Int32.Parse(string) in a try/catch block. What a pain. Int32.TryParse simultaneously tests the input string for integericity, returning a boolean, and outputs the integer result (zero if the string can't be parsed):

int i;

if (int.TryParse(CheckId, out i))


    //do stuff with i



blog comments powered by Disqus

Month List