Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better to use: Convert.ToX or X.Parse(...)?

I'm using reflection to create some objects. The values I'm setting are read in from a file so they're natively in a string format and I need to convert them to the datatype of the property.

My question is, which is faster/better to use: the Convert.ToX(...) methods or the X.Parse(...) methods?

like image 602
Micah Avatar asked May 12 '11 14:05

Micah


2 Answers

They are exactly the same! The Convert.ToX(String) methods actually call the X.Parse(String) methods.

like image 42
Cory Nelson Avatar answered Oct 18 '22 14:10

Cory Nelson


All of the Convert.ToX functions that accept an argument of type string ultimately call down to the Parse method of the appropriate datatype anyway.

For example, Convert.ToInt32(string) looks something like this:

public static int ToInt32(string value)
{
   if (value == null)
   {
      return 0;
   }
   return int.Parse(value, CultureInfo.CurrentCulture);
}

The same thing for all of the other numeric conversion methods, including Decimal and DateTime. So it's fairly irrelevant which one you use; the result (and speed) will be the same in either case.

Really, the only difference is the if (value == null) guard clause at the beginning. Whether or not that's convenient depends on the specific use case. Generally, if you know that you have a non-null string object, you might as well use Parse. If you're not sure, ConvertToX is a safer bet, requring less null-checking code inline.

like image 82
Cody Gray Avatar answered Oct 18 '22 14:10

Cody Gray