How to convert a string to an int in C#

 
following examples show different ways for converting a string to an integer type.

This example use Convert.ToInt32(String) method to convert an input string to an int .

            int num;
            string str = "4567";
            try
            {
                num = Convert.ToInt32(str);
            }
            catch (FormatException ex)
            {
                 MessageBox.Show("this is not valid number");
            }

This example use Int32.Parse() method to convert an input string to an int .

            int num;
            string str = "4567";
            try
            {
                num = Int32.Parse(str);
            }
            catch (FormatException ex)
            {
                 MessageBox.Show("this is not valid number");
            }

This example use Int32.TryParse() method to convert an input string to an int .TryParse returns true if the conversion succeeded and stores the result in the specified variable

            int num;
            string str = "4567";
            bool isSuccess = Int32.TryParse(str, out num);
 
            if (!isSuccess)
            {
                MessageBox.Show("error during parse");
            }