Reading input and writing output
Course contents (16 lessons)
- Getting started
- Installing the .NET 10 SDK and checking it works
- Your first console app and top-level statements
- The building blocks
- Variables and basic types
- Working with strings and interpolation
- Reading input and writing output
- Making decisions and repeating work
- Conditionals and switch expressions
- Loops: for, while, do and foreach
- Collections and methods
- Arrays and List of T
- Writing your own methods
- Objects and classes
- Classes and objects
- Properties, encapsulation and object initialisers
- Handling null safely
- Errors and files
- Exceptions: try, catch, finally and throw
- Reading and writing files
- Final project: expense tracker
- Expense tracker, part 1: planning, model and storage
- Expense tracker, part 2: the menu and summaries
Programs need to talk to people
Until now our programs only printed things. A useful program also asks questions. In a console app, Console.ReadLine() waits for the user to type a line and press Enter, then gives you what they typed as a string.
Console.Write("What is your name? ");
string? name = Console.ReadLine();
Console.WriteLine($"Nice to meet you, {name}.");
Two things to notice. Console.Write prints without moving to a new line, so the answer is typed next to the question. And the type is string?, with a question mark. That means the value can be null. ReadLine returns null when the input stream has ended, for example when the user presses Ctrl+Z on Windows or when input is piped from a file. We will cover this in the null lesson. For now, remember it.
Everything typed is text
If you ask for an age and the user types 34, you receive the string "34". You cannot do arithmetic with it until you convert it. int.Parse converts, but it throws an exception if the text is not a number. Users type all kinds of things, so use TryParse. It returns true or false and gives you the number through an out variable.
Console.WriteLine("Simple price calculator");
Console.WriteLine("-----------------------");
Console.Write("Product name: ");
string product = Console.ReadLine() ?? "";
int quantity;
while (true)
{
Console.Write("Quantity: ");
string? text = Console.ReadLine();
if (int.TryParse(text, out quantity) && quantity > 0)
{
break;
}
Console.WriteLine("Please enter a whole number greater than zero.");
}
decimal price;
while (true)
{
Console.Write("Unit price: ");
if (decimal.TryParse(Console.ReadLine(), out price) && price >= 0)
{
break;
}
Console.WriteLine("Please enter a valid price, for example 12.50.");
}
decimal total = quantity * price;
Console.WriteLine();
Console.WriteLine($"{product}: {quantity} x {price:N2} = {total:N2}");
Walking through it
The first question uses ?? "". This is the null-coalescing operator. It means "use the value on the left, but if it is null, use the value on the right". So product is always a real string.
The quantity question is wrapped in a while (true) loop. That looks like an endless loop, and it would be, except for break. The loop asks again and again until the user gives a valid answer, then break leaves it. Inside, int.TryParse(text, out quantity) tries to convert. If it works, the number is stored in quantity and the method returns true. The && means "and", so we also require that the number is above zero.
Loops are covered properly soon, so do not worry if this pattern is new. Type the code, run it, and try bad input such as letters or an empty line. Watch how the program refuses and asks again. That behaviour is called input validation, and it separates a toy program from a usable one.
Culture and decimals
decimal.TryParse uses the settings of the machine it runs on. On a machine set to a region that uses a comma as the decimal separator, 12,50 is accepted and 12.50 may not be. For a learning project that is fine. For real software, pass CultureInfo.InvariantCulture when the format must be fixed.
Other console features
Console.ReadKey()waits for a single key press.Console.Clear()clears the screen.Console.ForegroundColor = ConsoleColor.Green;changes text colour. CallConsole.ResetColor()after.Console.Error.WriteLinewrites to the error stream, which is where error messages belong.
Common mistakes
- Using
Parseon user input. One stray letter crashes the program. - Forgetting the answer is a string.
"5" + "3"is"53", not 8. - Not validating. A negative quantity or an empty name will cause strange results later.
- Ignoring the null warning on
ReadLine. It is there for a reason.
Try it yourself
- Write a program that asks for the user's birth year and prints their age this year. Reject years in the future.
- Ask for two numbers and print their sum, difference, product and quotient. Handle division by zero by printing a message instead.
- Add a colour: print the total in green.
Console.WriteLine("Simple price calculator");
Console.WriteLine("-----------------------");
Console.Write("Product name: ");
string product = Console.ReadLine() ?? "";
int quantity;
while (true)
{
Console.Write("Quantity: ");
string? text = Console.ReadLine();
if (int.TryParse(text, out quantity) && quantity > 0)
{
break;
}
Console.WriteLine("Please enter a whole number greater than zero.");
}
decimal price;
while (true)
{
Console.Write("Unit price: ");
if (decimal.TryParse(Console.ReadLine(), out price) && price >= 0)
{
break;
}
Console.WriteLine("Please enter a valid price, for example 12.50.");
}
decimal total = quantity * price;
Console.WriteLine();
Console.WriteLine($"{product}: {quantity} x {price:N2} = {total:N2}");
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account