February 12, 2007

Weekly WTF: Get Number From Query String

This is from some ancient code that is going bye-bye very quickly...
object o = Request.QueryString["eid"];
string strEId = ((o == null) ? string.Empty : o.ToString());
int eid = Convert.ToInt32(strEId);
So, what's the problem here?

Well, first off, the following code does the exact same thing without all of the unnecessary conversions:
int eid = Convert.ToInt32(Request.QueryString["eid"]);
...but you still have to wrap it in a try/catch block in case someone modifies the query string so that it passes in a non-numeric query string value.

The more cruft I strip away, the cleaner the code feels.

7 comments:

Sarkie said...

Well since I am awesome I will say a few things.

Won't Convert.ToInt32 die if the string is empty, so their code will die anyway.

Can't you update the Request.QueryString method to return something better?

Why do they seem to love ? : statements, not very readable.

Michael Russell said...

If a string is empty or null, Convert.ToInt32 returns a zero.

Request.QueryString is a built-in ASP.NET function that always returns a string.

Sarkie said...

ah ok, but I just tried it and it throws a

FormatException


value does not consist of an optional sign followed by a sequence of digits (zero through nine).

:)

c#

Michael Russell said...

I fully believe you. This is code I've got in a try-catch block that works without a problem if the query string doesn't exist, or if the query string exists and is proper:

int zip = Convert.ToInt32(Request.QueryString["zip"]);
if (0 != zip)
...

And based on a quick test, I was slightly incorrect. If the value is null, it returns a zero. If the value is empty or non-numeric, it throws an exception.

Regardless, that's what the try-catch block is for...the unexpected. ;)

Sarkie said...

Yeah :) I saw the need for it mate.

try
{

string empty = string.Empty;

int ints = Convert.ToInt32(empty);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

This is for anyone to see :)

But yeah, sounds like you are loving it. Talk soon :)

Kartones said...

mm, why don't you use the new .NET 2.0 TryParse?

int myNumber;
if (int.TryParse(myString, out myNumber))
{
... (all ok, number has its value set by tryparse)
}
else
{
... (assign manually a value, error handling, and such)
}

This won't let string.Empty pass, but no manual try-catch is needed

Michael Russell said...

Because we're stuck on ASP.NET 1.1 because of some of the components we have to use.