Converting Value Types

Converting a type like a string to an value type like integer, can easily cause an exception, which is a huge performance killer.  Hopefully you have wrapped the conversion in a Try Catch block, if not your program could take a nose dive and your users will be upset.

Consider the code below that converts an http query parameter to an integer.

int nodeId;
if  (Request.Params.AllKeys.Contains("nodeId" ))
{
  nodeId = Convert.ToInt16(Request.Params["nodeId" ]);
}
else
{
  return ;
}

As you can see, if a non numeric values is passed it, an Exception will be thrown (removed Try Catch for brevity).  The code should be refactored to this:

int nodeId;
if  (!Request.Params.AllKeys.Contains("nodeId" ))
{
  return ;
}
if  (int.TryParse(Request.Params["nodeId" ], out  nodeId) == false )
{
  return ;
}

In this code, we are using TryParse to parse the string to an integer that returns true if the conversion succeeded. This is guaranteed not to cause an exception, which you want to avoid at all costs in your application.

Tip By: David McCarter