tags:

views:

50

answers:

2

Hello.

intID1 = Int32.Parse(myValue.ToString());
intID2 = Convert.ToInt32(myValue);

Which one is better and why?

+4  A: 

They are exactly the same, except that Convert.ToInt32(null) returns 0.

Convert.ToInt32 is defined as follows:

    public static int ToInt32(String value) {
        if (value == null) 
            return 0;
        return Int32.Parse(value, CultureInfo.CurrentCulture);
    }
SLaks
@SLaks, Where do you find ToInt32() function source code? I googled MSDN and can't find the details like you input. :-)
Nano HE
@Nano: http://referencesource.microsoft.com/ or http://en.wikipedia.org/wiki/Shared_Source_Common_Language_Infrastructure
SLaks
Also Reflector is an option: http://www.red-gate.com/products/reflector/
APShredder
+1  A: 

Well, Reflector says...

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

public static int Parse(string s)
{
    return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}

So they're basically the same except that Convert.ToInt32() does an added null check.

APShredder