tags:

views:

61

answers:

4

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

+1  A: 

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.

Nick Craver
Beat me again by exactly one second ... :-)
SLaks
+3  A: 

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)

SLaks
Thanks for your answer +1. Could you please tell me where to find the c# source for some methods?
hkda150
Reflector (http://www.red-gate.com/products/reflector/) or the .Net Reference Source (http://referencesource.microsoft.com/)
SLaks
A: 

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

JDMX
+2  A: 

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.

Nick