Reading Console Input
Console.ReadLine waits for the user to type a line and press Enter, then returns it as a string.
How it works
Read what the user types with Console.ReadLine and convert it safely with int.TryParse.
ReadLine can return null when input ends, so ?? supplies a default. int.TryParse returns false instead of throwing when the text is not a number. In the online compiler, type your answers when the prompts appear.
Runnable C# example
Program.cs
using System;
class Program
{
static void Main()
{
// Console.ReadLine returns the typed line, or null when input ends.
Console.Write("What is your name? ");
string name = Console.ReadLine() ?? "friend";
// int.TryParse converts text safely instead of throwing on bad input.
Console.Write("How old are you? ");
string text = Console.ReadLine() ?? "";
if (int.TryParse(text, out int age))
{
Console.WriteLine($"Hello, {name}!");
Console.WriteLine($"In 10 years you will be {age + 10}.");
}
else
{
Console.WriteLine($"\"{text}\" is not a whole number.");
}
}
}
What is your name? Ada
How old are you? 29
Hello, Ada!
In 10 years you will be 39.Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Average of Three Average three whole numbers. Easy
- Celsius to Fahrenheit Convert a temperature from Celsius to Fahrenheit. Easy