Thursday, June 11, 2009

To TryParse or not, is it a question?

Use TryParse when converting a string to a ValueType.

Why?
There´s really no reason not to, it is:
- faster.
- safer, you will not have to be bothered with exceptions.
- easy, for all but DateTime.
and it will always work, unless you want an exception to be propagated.

Using Xxx.Parse or Convert.ToXxx will throw an exception if the string is not valid for conversion.
You may think that when an invalid value is rare the Xxx.Parse or Convert.ToXxx is not gonna throw an exception and it will be faster for most cases.

If you do, my opinion is you´re wrong.
Throwing exceptions when you can avoid it is bad practice and (cpu)time consuming.
Making it a habit to ignore this sort of basic rules is going to lead to other bad decisions when writing code.

I have tried it my self but I have no data to support it.
Others have, look at the result they´ve made:

Parsing Performance @stackoverflow
TryParse and the Exception Tax @codinghorror
int.Parse for Integer Conversion in C# @dotnetperls


Examples
public static Int32 ToInt32(string text)
{
   Int32 result;
   if (Int32.TryParse(text, out result))
   {
       return (result);
   }
   return (0);
}
The only reason to convert to a data type from string and depending on try-catch is if you are using a method with a generic data type as input and you know that invalid values is rare.
public static T ConvertToType<T>(string text)
{
   try
   {
       if (string.IsNullOrEmpty(text))
       {
           return (default(T));
       }
       return (T)Convert.ChangeType(text, typeof(T), CultureInfo.CurrentUICulture);
   }
   catch
   {
       return (default(T));
   }
}
Or a general method for conversion of string to an unknown(at design time) datatype:
public static object ConvertToType(string text, Type type)
{
   object defaultValue = GetDefault(type);
   try
   {
       if (string.IsNullOrEmpty(text))
       {
           return (defaultValue);
       }
       return (Convert.ChangeType(text, type, CultureInfo.CurrentUICulture));
   }
   catch
   {
       return (defaultValue);
   }
}


Conclusion
Use TryParse if you don´t want an exception to propagate or you want to use a generic method and you know that an invalid value is rare.

1 comment:

  1. Anonymous09:10

    OMG ... that's a pretty important observation...keep up the good work!

    ReplyDelete