Question

For instance, in the following scenario

Convert.Int64(string somstring)

or

long.Parse(string somstring);

appear to be doing same kind of work. Which one is a better practice ?

Thanks

Was it helpful?

Solution

If you look at the source, Convert.ToInt64(string) simply calls long.Parse, but checks that the string isn't null first.

I would recommend callings long.Parse because it makes the intent (string parsing) clearer.

I recommend using the Convert class if the type that you're converting from might change. (Or if you're converting from object)

OTHER TIPS

Just for completeness to the other answers, don't forget about long.TryParse which is generally safer if you are unsure of the input string format.

Convert.Int64 calls long.Parse internally, just does a null check before. Here's the guts:

if (value == null)
{
    return 0L;
}
return long.Parse(value, CultureInfo.CurrentCulture);

If you need the null check, Convert.Int64 is safer that's all, otherwise no difference.

Convert.Int64 actually calls long.Parse with the CultureInfo.CurrentCulture after first doing a null check on the string. So as long as you know the string is not going to be null, you can save the step and call long.Parse

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top