Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. String to int

String to int

Scheduled Pinned Locked Moved C#
csharpsysadminxmlquestion
16 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M musefan

    int result; int.TryParse("10000", out result);

    Life goes very fast. Tomorrow, today is already yesterday.

    M Offline
    M Offline
    Michael Bookatz
    wrote on last edited by
    #4

    what's the difference between the method you've used and result = int.parse("100000");

    M M M 3 Replies Last reply
    0
    • D DaveyM69

      musefan has given you the perfect answer. Just be aware that if the number can't be converted to an int you will get zero. I have an extension method that I use when working with text/xml etc files to simplify stuff.

      public static class ExtensionMethods
      {
      /// <summary>
      /// Converts a string to an integer.
      /// </summary>
      /// <param name="value">The string to convert.</param>
      /// <returns>The integer value of the string if valid; otherwise, zero.</returns>
      public static Int32 ToInt32(this string value)
      {
      int result;
      Int32.TryParse(value, out result);
      return result;
      }
      }

      Now I can can just use something like

      int intFromFile = stringFromFile.ToInt32();

      Dave
      BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
      Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

      G Offline
      G Offline
      Greg Chelstowski
      wrote on last edited by
      #5

      If I might... Is it considered really bad practice to do Convert.ToInt32 ? I have seen stuff (and well, I have used it, too) like:

      string x = "10";
      int xInt;
      try
      {
      xInt = Convert.ToInt32(x);
      }
      catch
      {
      xInt = 0;
      }

      Would that not do the same as TryParse? Or is it an unnecessary way around it, or simply, crap?

      var question = (_2b || !(_2b));

      D 1 Reply Last reply
      0
      • M Michael Bookatz

        what's the difference between the method you've used and result = int.parse("100000");

        M Offline
        M Offline
        Mohammad Dayyan
        wrote on last edited by
        #6

        there is no difference

        1 Reply Last reply
        0
        • M Michael Bookatz

          what's the difference between the method you've used and result = int.parse("100000");

          M Offline
          M Offline
          musefan
          wrote on last edited by
          #7

          The difference is that if you pass a string to int.parse() that is not a valid string (contains noon-numeric characters) it will throw an exception that you will need to manually handle. If you use my method the error is handled automatically and the result is set to 0, its up to you if you want to handle the error yourself thou, depends how much validation control you need. if you are expecting the result could sometimes be 0 as a result then you may be best to handle the error yourself. but in the case of a port number you shouldnt need to do this, just check if result is 0 for an error.

          Life goes very fast. Tomorrow, today is already yesterday.

          M D 2 Replies Last reply
          0
          • M Michael Bookatz

            what's the difference between the method you've used and result = int.parse("100000");

            M Offline
            M Offline
            Mirko1980
            wrote on last edited by
            #8

            If the input string is not a valid integer, int.Parse throws an exception, while int.TryParse returns false without setting result value. e.g.

            string wrong = "xyz";
            result = int.Parse(wrong); // an exception is thrown here

            string wrong = "xyz";
            int result = -1;
            bool success = int.TryParse(wrong, out result); // success is false, while result will still be -1

            M 1 Reply Last reply
            0
            • M musefan

              The difference is that if you pass a string to int.parse() that is not a valid string (contains noon-numeric characters) it will throw an exception that you will need to manually handle. If you use my method the error is handled automatically and the result is set to 0, its up to you if you want to handle the error yourself thou, depends how much validation control you need. if you are expecting the result could sometimes be 0 as a result then you may be best to handle the error yourself. but in the case of a port number you shouldnt need to do this, just check if result is 0 for an error.

              Life goes very fast. Tomorrow, today is already yesterday.

              M Offline
              M Offline
              Michael Bookatz
              wrote on last edited by
              #9

              Thank you for the reply... next time I convert I'll bare it in mind.

              1 Reply Last reply
              0
              • M Mirko1980

                If the input string is not a valid integer, int.Parse throws an exception, while int.TryParse returns false without setting result value. e.g.

                string wrong = "xyz";
                result = int.Parse(wrong); // an exception is thrown here

                string wrong = "xyz";
                int result = -1;
                bool success = int.TryParse(wrong, out result); // success is false, while result will still be -1

                M Offline
                M Offline
                Michael Bookatz
                wrote on last edited by
                #10

                Thanks for the reply, however according to the above post the result would be set to zero and not stay at -1 or is it only set to zero if there is no valid number in it?

                M D 2 Replies Last reply
                0
                • M Michael Bookatz

                  Thanks for the reply, however according to the above post the result would be set to zero and not stay at -1 or is it only set to zero if there is no valid number in it?

                  M Offline
                  M Offline
                  Mirko1980
                  wrote on last edited by
                  #11

                  Yes, I was wrong, int.TryParse puts 0 in the result if the parsing fails. For some reason, I tought that the resul value was unchanged in case of failure, my bad.

                  M 1 Reply Last reply
                  0
                  • M musefan

                    The difference is that if you pass a string to int.parse() that is not a valid string (contains noon-numeric characters) it will throw an exception that you will need to manually handle. If you use my method the error is handled automatically and the result is set to 0, its up to you if you want to handle the error yourself thou, depends how much validation control you need. if you are expecting the result could sometimes be 0 as a result then you may be best to handle the error yourself. but in the case of a port number you shouldnt need to do this, just check if result is 0 for an error.

                    Life goes very fast. Tomorrow, today is already yesterday.

                    D Offline
                    D Offline
                    DaveyM69
                    wrote on last edited by
                    #12

                    musefan wrote:

                    just check if result is 0 for an error

                    Better to assign and check the boolean return value of the TryParse method before working with the value. Still preferable to catching an exception!

                    Dave
                    BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                    Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

                    M 1 Reply Last reply
                    0
                    • M Mirko1980

                      Yes, I was wrong, int.TryParse puts 0 in the result if the parsing fails. For some reason, I tought that the resul value was unchanged in case of failure, my bad.

                      M Offline
                      M Offline
                      Michael Bookatz
                      wrote on last edited by
                      #13

                      No worries thanks for the clarification

                      1 Reply Last reply
                      0
                      • M Michael Bookatz

                        Thanks for the reply, however according to the above post the result would be set to zero and not stay at -1 or is it only set to zero if there is no valid number in it?

                        D Offline
                        D Offline
                        DaveyM69
                        wrote on last edited by
                        #14

                        hopingToCode wrote:

                        only set to zero if there is no valid number

                        ... or if the number in the text is zero! Check the return value of the TryParse method to determine if successful.

                        Dave
                        BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                        Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

                        1 Reply Last reply
                        0
                        • D DaveyM69

                          musefan wrote:

                          just check if result is 0 for an error

                          Better to assign and check the boolean return value of the TryParse method before working with the value. Still preferable to catching an exception!

                          Dave
                          BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                          Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

                          M Offline
                          M Offline
                          musefan
                          wrote on last edited by
                          #15

                          Ahh yes, i forgot TryParse() returns a bool

                          Life goes very fast. Tomorrow, today is already yesterday.

                          1 Reply Last reply
                          0
                          • G Greg Chelstowski

                            If I might... Is it considered really bad practice to do Convert.ToInt32 ? I have seen stuff (and well, I have used it, too) like:

                            string x = "10";
                            int xInt;
                            try
                            {
                            xInt = Convert.ToInt32(x);
                            }
                            catch
                            {
                            xInt = 0;
                            }

                            Would that not do the same as TryParse? Or is it an unnecessary way around it, or simply, crap?

                            var question = (_2b || !(_2b));

                            D Offline
                            D Offline
                            DaveyM69
                            wrote on last edited by
                            #16

                            Not bad practice, possibly a little slower going via the Convert class but I would have to check the implementation to be sure. The convert class is great for converting from a built in type to another (not just from string), but I would guess the Int32.Parse or Int32.TryParse methods would be perhaps a little more efficient.

                            Dave
                            BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                            Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups