Skip to main content

Inputs

To ask a user for information, you need two steps:

  • Prompt: tell the user what to type
  • Read: capture what they typed from the console

This is commonly called "prompting for input." (as seen in all gen AI tools lol)

You already know how to prompt using Console.WriteLine() or Console.Write(). Reading input is done with Console.ReadLine().

Console.ReadLine()​

Console.ReadLine() pauses the program until the user types something and presses Enter. It ALWAYS returns a string, so you ALWAYS need a string variable to store the result:

string name; // create a string variable called 'name';
Console.Write("Enter your name: "); // prompt the user
name = Console.ReadLine(); // read what the user typed and store in 'name'

Console.WriteLine($"Hi {name}, isn't programming cool ?");

Console.Write() is the cleanest choice for prompts since it doesn't add a line break between the prompt and the user's typed input ✨

Numbers as Input​

Console.ReadLine() always returns a string, even if we don't want it to. That means you can't use it directly in math:

int myAge = 29;
string userInput;

Console.Write("Enter your age: ");
userInput = Console.ReadLine();

int ageDifference = myAge - userInput; // ❌ ERROR
Console.WriteLine($"I am {ageDifference} years older than you.");

Here we can't subtract a string from an int, so we need to convert the string to a number first with int.Parse():

int myAge = 29;
string userInput;

Console.Write("Enter your age: ");
userInput = Console.ReadLine();

int ageDifference = myAge - int.Parse(userInput); // FIXED 💅
Console.WriteLine($"I am {ageDifference} years older than you.");

The same idea applies with double.Parse():

string userInput;

Console.Write("How many digits of PI do you know: ");
userInput = Console.ReadLine();

double piDifference = Math.PI - double.Parse(userInput);
Console.WriteLine($"You were {piDifference} off :^(");

⚠️ If the input can't be converted to a number, Parse() WILL crash you program 💥