Loading lessons...
User Input
User Input
You can read what the user types using the Console class.
Read a line of text
Console.ReadLine() reads the next line the user types:
Console.WriteLine("Enter username:");
string userName = Console.ReadLine();
Console.WriteLine("Username is: " + userName);
Read a number
Console.ReadLine() always returns a string. To work with a number, convert it:
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
Parse vs Convert
Both int.Parse() and Convert.ToInt32() turn text into an int:
int a = int.Parse("10");
int b = Convert.ToInt32("10");
If the input isn't a valid number, these throw an exception - you'll learn to handle that later.
Simple calculator example
Console.WriteLine("Enter x:");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter y:");
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Sum is: " + (x + y));
TL;DR
Console.ReadLine()reads a line of text (a string).- Convert the string with
Convert.ToInt32()to get a number. - ReadLine always returns a string first.