Guillermo G. Blog

Software Architect
ASP.NET MCP
"The best way to predict the future is to invent it"

Tip: Cast using the as Statement and Convert class vs Normal Casting

blackboard

Convert data from a DataType to another is a daily task of a developer; the applications require show formatted data (i.e Dates, currency, etc.) or make operations with this data. Here I'll show you an easy tip to avoid (or minimize) the use of try ... catch sentences when you need to do a casting or data conversion.

Normally to convert a numerical DataType to a string DataType (for example), we use the ToString() native method of the object. It's so easy and is the "natural" way to do it, but, what happens if the ToString() method can't do the conversion? It throws an Exception !!!

string
mySessionValue = Session["myKey"].ToString();
// if Session["myKey"] doesn't exists it throws an exception trying to convert null
// to string DataType.

Ok, a simple solution is to do the conversion using the as statement, this way it avoids to throw an exception if an error occurred when it's trying to do the conversion and a null value is assigned to mySessionValue variable.

string mySessionValue = Session["myKey"] as string;
// if Session["myKey"] doesn't exists it don't throw an exception trying to convert
//
null to string DataType.

Another valid solution using the ToString() method of the Convert class ...

string mySessionValue = Convert.ToString(Session["myKey"]);
// if Session["myKey"] doesn't exists it don't throw an exception trying to convert
//
null to string DataType.

And ... It's better to ask for a null value ...

if (string.IsNullOrEmpty(mySessionValue))
{
   // some code ...
}

Than to wrap the code with a try catch sentence.

try
{
   
string mySessionValue = Session["myKey"].ToString();
}
catch (InvalidCastException ex)
{
   
// Do something
}

I hope that this little and easy tip helps you to write better code.

Posted: Dec 05 2007, 11:46 AM by gugonzar | with 2 comment(s)
Filed under: , , ,

Comments

HQ said:

Excelente aporte!

# December 10, 2007 5:37 PM

Metalp said:

Awesome!!! that's just what i needed, thanks a lot!

# June 28, 2008 4:43 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)