Way to read input from console in C#


Use the ReadLine() method to read input from the console in C#. This method receives the input as string, therefore you need to convert it.

For example −

Let us see how to get user input from user and convert it to integer.

Firstly, read user input −

string val;
Console.Write("Enter integer: ");
val = Console.ReadLine();

Now convert it to integer −

int a = Convert.ToInt32(val);
Console.WriteLine("Your input: {0}",a);

Let us see this in an example. The input is added using command line argument−

Example

 Live Demo

using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      string val;
      Console.Write("Enter Integer: ");
      val = Console.ReadLine();
      int a = Convert.ToInt32(val);
      Console.WriteLine("Your input: {0}",a);
   }
}

The above will give the following result −

Enter Integer: 5
Your input: 5

Updated on: 20-Jun-2020

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements