c# convert string to int

c# convert string to int

You want to convert string to int using C#.net as a programming language.

Note: You can’t convert the alphanumeric string in to integer by direct method. If you try you will end up with run time Format exception.

Input string was not in a correct format.

namespace ConsoleDemo.App
{
    class Program
    {
        static void Main(string[] args)
        {


            var strName = "one";

            int val = Convert.ToInt32(strName);

            Console.WriteLine("Converted Value of string name  {0} is {1}", strName, val);

            Console.ReadLine();

        }

    }
}

To handle exception better use TryParse method.

namespace ConsoleDemo.App
{
    class Program
    {
        static void Main(string[] args)
        {


            var strName = "one";
            int result;
            var flag = int.TryParse(strName, out result);

            Console.WriteLine("Converted Value of string name  {0} is {1}", strName, result);

            Console.ReadLine();

        }

    }
}