convert string to number in c#

To convert a string into a number, we can use either Parse, TryParse, or Convert.Int32, or Convert.ToDouble, etc functions.

Here is an example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
    class Program
        static void Main(string[] args)
            int num1, num2, num3;
            string str1, str2;

            Console.WriteLine("Input first number: ");
            str1 = Console.ReadLine();

            Console.WriteLine("Input second number: ");
            str2 = Console.ReadLine();
      Console.WriteLine("Input third number: ");
            num3 = Convert.Int32(Console.ReadLine());
            if( int.TryParse(str1, out num1)== false || int.TryParse(str2, out num2)==false)
                Console.WriteLine("Input must be an integer");
             Console.WriteLine("The numbers are: " + num1 + " " + num2 + " " + num3);     


NOTE: when we write like “out num2” this means, we are passing the address of num2, not the actual value of num2


Add a Comment

Your email address will not be published. Required fields are marked *