Using the JScript Convert class to safely convert types

Posted Tuesday, January 10, 2006 8:38 AM by C-Dog's .NET Tip of the Day

This is nothing new to ASP.NET 2.0, but Scott mentioned its uses in one of his blog posts briefly. Take a look at the statement below.

int id = int32.Parse(Request.QueryString["Id"]);

If you have written anything like this before, you know that if Request.QueryString returns null, you are going to have a bad time. This is why in the past, I had created the WebConfiguration class to safely get these values without throwing an exception. Typically, you would have to write something like the sample below. Of course that still didn't prevent an exception from occuring if an int wasn't passed.

int id;
if (Request.QueryString["Id"] != null)
    id = int32.Parse(Request.QueryString["Id"];

Microsoft.JScript has long had a class called Convert with methods such as ToIn32(), ToDateTime(), etc. The nice thing about using ToInt32 for example is that if the value is null, it won't thrown an exception it will just return 0.

Now you can replace the above expression with something like this.

int id = Convert.ToInt32(Request.QueryString["Id"]);

It's a simple tip but maybe you will find it useful at some point.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=231