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?
They are exactly the same! The Convert.ToX(String)
methods actually call the X.Parse(String)
methods.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With