Codiqo

Learn C# · lesson 8 of 61 · about 8 minutes

Reading Input

Let the player choose: read their action and a potion with Console.ReadLine, turn text into numbers, and handle having no input.

What you'll learn

  • Read a line of input
  • Convert text with int.Parse and double.Parse
  • Handle a null line with ??

ReadLine

Console.ReadLine() returns the next line the player types, as a string. If there's no more input at all, it returns null, which means "nothing".

The ?? operator gives a fallback for null: string action = Console.ReadLine() ?? "";. Codiqo builds C# with warnings treated as errors, and leaving out ?? is a warning, so always add one.

A typed number is still text: "15". int.Parse turns it into an int, and double.Parse into a double.

The player's turn

string action = Console.ReadLine() ?? "";
int potion = int.Parse(Console.ReadLine() ?? "0");
Console.WriteLine($"Ada chooses {action} and drinks a potion: +{potion} HP");

Output

Ada chooses defend and drinks a potion: +15 HP

When there's no input at all

string name = Console.ReadLine() ?? "Hero";
Console.WriteLine($"Welcome, {name}!");

Output

Welcome, Hero!

Tip

int.Parse only understands whole numbers. Given ten or 1.5, it throws a FormatException and the program stops.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.