CodeBlanks Logo Icon CodeBlanks

Summary - Console I/O

C# course · Beginner · Lesson 99/116

Combine ReadLine, TryParse and formatting to write an interactive menu.

Summary - Console I/O

In this group you learned the core tools for console input and output. Console.ReadLine reads a line, Console.ReadKey reads a single key. When you need a number, int.Parse or double.Parse converts it; the safe way is TryParse.

To format output, you used string interpolation ($"...") and format specifiers (F2, X). These tools are the foundation of interactive console apps. In the next exercise you will try them all together.

Interactive flow

A typical interactive flow is: first print a cue with Console.Write, then read the input with Console.ReadLine, then convert safely with TryParse, and finally print the result with Console.WriteLine. This pattern appears everywhere, from small tools to large applications.

You can use this flow in small projects such as a shopping cart, a grade calculator, or a book list. In the next exercise you will apply this pattern.

Exercise Print a receipt line

Use product, quantity and price in a Console.WriteLine with string interpolation. The output should be "<product> - <quantity> items - <quantity * price> USD". Use a multiplication expression inside the curly braces.

Show example solution
Print with Console.WriteLine($"{product} - {quantity} items - {quantity * price} USD");
Example solution:
using System;

class Program
{
    static void Main()
    {
        string product = "Pen";
        int quantity = 2;
        int price = 5;
        Console.WriteLine($"{product} - {quantity} items - {quantity * price} USD");
    }
}

Test yourself

  1. Match each tool to its job

    Console.ReadLine
    Reads a line
    int.TryParse
    Safe integer
    double.Parse
    Converts decimal
    $"..."
    Interpolation
  2. Which is safest for user input?

    string input = Console.ReadLine();
    • int.Parse(input)
    • double.Parse(input)
    • int.TryParse(input, out n)
    • Convert.ToInt32(input)
    Show answer

    int.TryParse(input, out n) — Correct! TryParse never throws, so it is the safest way.

All lessons in Beginner