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

Which one is better and why?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Nano HE
  • 9,109
  • 31
  • 97
  • 137
  • possible duplicate of [.Net Parse versus Convert](http://stackoverflow.com/questions/18465/net-parse-versus-convert) – JasonMArcher Oct 20 '14 at 16:44

3 Answers3

37

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
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Where do you find ToInt32() function source code? I googled MSDN and can't find the details like you input. :-) – Nano HE Sep 15 '10 at 01:07
  • 4
    @Nano: http://referencesource.microsoft.com/ or http://en.wikipedia.org/wiki/Shared_Source_Common_Language_Infrastructure – SLaks Sep 15 '10 at 01:08
6

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.

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
Adam P
  • 4,603
  • 6
  • 31
  • 40
0

It depends on what you mean by "better" because "better" is subjective.

For instance - code readability. Some people prefer to see "Convert" in their code; others prefer to see "Parse".

In terms of speed, they're also both roughly equal according to these benchmarks.

Or do you always wants a value returned? As others have mentioned, ConvertTo returns a 0 (zero) for null values whereas you don't get that option with Parse.

Free Coder 24
  • 933
  • 9
  • 12