Labs ICT
โญ Pro Login

Input & Output

Programs are boring if they can't talk to you. C# makes input and output easy with the Console class. Think of the console as a chat window between your program and your user.

Writing to the Console

Console.WriteLine prints text and moves to the next line. Console.Write prints text but stays on the same line:


Console.WriteLine("Line 1");   // Prints "Line 1" then goes to next line
Console.Write("Still on ");    // Prints without newline
Console.WriteLine("Line 2");   // Prints "Line 2" after "Still on "
    

Output:


Line 1
Still on Line 2
    

Reading Input from the User

Console.ReadLine reads whatever the user types until they press Enter. It returns a string:


Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");
    

When the program runs, it waits at ReadLine for the user to type something. Nothing happens until they press Enter.

If you're reading a number, remember it comes back as a string. You'll need to parse it:


Console.Write("Enter your age: ");
string input = Console.ReadLine();
int age = int.Parse(input);
Console.WriteLine("Next year you'll be " + (age + 1));
    

String Interpolation

Concatenating strings with + works, but C# has a cleaner way. String interpolation uses $ before the string and lets you embed variables directly with curly braces:


string name = "Lisa";
int age = 30;

// Old way with concatenation
Console.WriteLine("Hello, " + name + "! You are " + age + " years old.");

// New way with interpolation
Console.WriteLine($"Hello, {name}! You are {age} years old.");
    

Both lines print the same thing, but interpolation is easier to read and less error-prone. You can even put expressions inside the braces:


Console.WriteLine($"Next year you'll be {age + 1}");
Console.WriteLine($"Pi is approximately {Math.PI:F2}");  // F2 formats to 2 decimals
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which method reads a line of text from the console?