C# User Input
The Console.ReadLine() method reads a line of text typed by the user from the console. It always returns a string, even if the user types a number.
To use the input as a number, you must convert it using Convert.ToInt32(), int.Parse(), or similar methods, since C# is strongly typed.
string input = Console.ReadLine();
int number = Convert.ToInt32(input);Reading text input
Console.ReadLine() pauses the program and waits for the user to type something and press Enter. The typed text is returned as a string.
Reading numeric input
Since ReadLine() returns a string, you need to convert it to a number type before doing math, using Convert.ToInt32() or int.Parse().
using System;
class Program {
static void Main() {
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
}
}Enter your name:
Hello, AmyThe user types 'Amy', and it is printed back in a greeting.
using System;
class Program {
static void Main() {
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You entered: " + num);
}
}Enter a number:
You entered: 7The string input is converted to an int using Convert.ToInt32() before being used.
Key points
- Console.ReadLine() reads a line of input as a string.
- Numeric input must be converted before doing math.
- Convert.ToInt32() and int.Parse() convert strings to integers.
- The program pauses at ReadLine() until the user presses Enter.
