Discussion

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul

    #1

    Discussion

    string mynumberstring = "123";
    int mynumber;
    mynumber = int.Parse(mynum berstring);
    mynumber = Convert.ToInt32 (mynumberstring );

    Both seem to have the same effect. But whats the
    difference and which is 'best'?

    Thanks, Paul.
  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: Discussion

    Paul,

    Int32.Parse has the most flexibility, with the capability of passing in
    a string, a value from the NumberStyles enumeration, and a format provider.
    ToInt32 will only accept the string and a format provider. The Convert
    class has the advantage of being able to take any type and trying to convert
    to an Int32 (not always successful though).

    So, you should pick the one that suits your needs best and then use
    that. I don't know if there is a perf difference, but I am sure someone can
    run some tests.

    Hope this helps.


    --
    - Nicholas Paldino [.NET/C# MVP]
    - nicholas.paldin o@exisconsultin g.com

    "Paul" <qwe@qwe.com> wrote in message
    news:0bf601c351 cd$c076e9f0$a30 1280a@phx.gbl.. .[color=blue]
    > string mynumberstring = "123";
    > int mynumber;
    > mynumber = int.Parse(mynum berstring);
    > mynumber = Convert.ToInt32 (mynumberstring );
    >
    > Both seem to have the same effect. But whats the
    > difference and which is 'best'?
    >
    > Thanks, Paul.[/color]


    Comment

    • Nicholas Paldino [.NET/C# MVP]

      #3
      Re: Discussion

      Paul,

      I ran my own tests (just a loop), and I ran each one for ten million
      times. I found there to be a slight advantage in the call to Int32.Parse,
      by about .2 - .4 seconds. Unless you are doing an ungodly amount of
      conversions, I wouldn't worry about it.


      --
      - Nicholas Paldino [.NET/C# MVP]
      - nicholas.paldin o@exisconsultin g.com

      "Paul" <qwe@qwe.com> wrote in message
      news:0bf601c351 cd$c076e9f0$a30 1280a@phx.gbl.. .[color=blue]
      > string mynumberstring = "123";
      > int mynumber;
      > mynumber = int.Parse(mynum berstring);
      > mynumber = Convert.ToInt32 (mynumberstring );
      >
      > Both seem to have the same effect. But whats the
      > difference and which is 'best'?
      >
      > Thanks, Paul.[/color]


      Comment

      Working...