Andornot Consulting Inc.
Home Page
Home Page
 |  | 

Thursday, November 02, 2006

Query String tips with C# 2.0

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

}

4 Comments:

Anonymous Dmitry Lomov said...

Peter,
thanks for nice words about ReSharper.
We are currently working on a ReSharper 2.5, which will bring in some support for VB.NET, and we are desperately in need of opinion on that from the seasoned VB developers.

So if you still code in VB.NET from time to time, you are most welcome to try it out. The download link is ReSharper 2.5 EAP .

Friendly,
Dmitry Lomov
Senior Software Developer
JetBrains Inc.

12:05 PM  
Anonymous Will said...

if ( !String.IsNullOrEmpty(foo) ) should also work instead of == false.

10:16 AM  
Anonymous Anonymous said...

TryParse is handy, but I prefer to use a Regex.IsMatch(Request.QueryString("Id"), "[0-9]*") within my "if" statement to see if the value is an integer or not.

2:47 PM  
Blogger Joe Bailey said...

Thanks. I just happened to start a new app in c#. We were adding new code for a page that may or may not use some values. It threw me for a second because most of our pages know the values are coming, but this article helped.

joebailey.org

8:44 AM  

Post a Comment

<< Home