How do I ask the user for input in C#

user7316312 picture user7316312 · Feb 21, 2017 · Viewed 41.5k times · Source

I am switching from Python to C# and I am having trouble with the ReadLine() function. If I want to ask a user for input Python I did it like this:

x = int(input("Type any number:  ")) 

In C# this becomes:

int x = Int32.Parse (Console.ReadLine()); 

But if I type this I get an error:

int x = Int32.Parse (Console.ReadLine("Type any number:  "));

How do I ask the user to type something in C#?

Answer

Roman Doskoch picture Roman Doskoch · Feb 21, 2017

You should change this:

int x = Int32.Parse (Console.ReadLine("Type any number:  "));

to this:

Console.WriteLine("Type any number:  "); // or Console.Write("Type any number:  "); to enter number in the same line
int x = Int32.Parse(Console.ReadLine());

But if you enter some letter(or another symbol that cannot be parsed to int) you will get an Exception. To check if entered value is correct:

(Better option):

Console.WriteLine("Type any number:  ");
int x;
if (int.TryParse(Console.ReadLine(), out x))
{
    //correct input
}
else
{
    //wrong input
}