How to read inputs as integers in C#?




To read inputs as integers in C#, use the Convert.ToInt32() method.

res = Convert.ToInt32(val);

Let us see how −

The Convert.ToInt32 converts the specified string representation of a number to an equivalent 32-bit signed integer.

Firstly, read the console input −

string val;
val = Console.ReadLine();

After reading, convert it to an integer.

int res;
res = Convert.ToInt32(val);

Let us see an example −

Example

 Live Demo

using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      string val;
      int res;
   
      Console.WriteLine("Input from user: ");
      val = Console.ReadLine();

      // convert to integer
      res = Convert.ToInt32(val);

      // display the line
      Console.WriteLine("Input = {0}", res);
   }
}

Output

Input from user:
Input = 0

The following is the output. The input is entered by the user.

Input from user: 2
Input = 2

Advertisements