Chapter 8: User Input and Output
1. Output – Showing Text to the User (Console.WriteLine & Friends)
You already know Console.WriteLine() – it’s the most common way to print text.
But there are several useful variations:
| Method | What it does | Example | Result on screen |
|---|---|---|---|
| Console.WriteLine() | Print text + new line | Console.WriteLine(“Hello”); | Hello (cursor moves to next line) |
| Console.Write() | Print text without new line | Console.Write(“Hi”); Console.Write(“!”); | Hi! (all on same line) |
| Console.WriteLine(“text”) | With formatting | Console.WriteLine(“Age: {0}”, 25); | Age: 25 |
| Console.WriteLine($”…”) | String interpolation (modern & best) | Console.WriteLine($”Hi {name}!”); | Hi Webliance! |
Real example – Beautiful output:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
var name = "Webliance"; var city = "Hyderabad"; var age = 25; Console.WriteLine("╔════════════════════════════════════╗"); Console.WriteLine($"║ Welcome, {name}! ║"); Console.WriteLine($"║ From: {city,-20} Age: {age} ║"); Console.WriteLine("╚════════════════════════════════════╝"); |
2. Input – Getting Data from the User (Console.ReadLine)
The only way to read a full line of text from the console is:
|
0 1 2 3 4 5 6 |
string input = Console.ReadLine(); |
- It waits until the user presses Enter
- Returns everything the user typed as a string
- Never returns null in modern .NET (it returns empty string “” if user just presses Enter)
Important: Console.ReadLine() always returns a string – even if the user types a number!
3. Parsing – Converting String to Numbers (Very Important!)
Because input is always string, you need to convert it to int, double, etc.
Here are the most common & safe ways:
| Method | Use when | Example | Throws exception if invalid? |
|---|---|---|---|
| int.Parse(string) | You are 100% sure input is valid | int age = int.Parse(“25”); | Yes |
| Convert.ToInt32(string) | Same as above | int age = Convert.ToInt32(“25”); | Yes |
| int.TryParse(string, out int) | Safest – recommended in real apps | if (int.TryParse(input, out int age)) { … } | No – returns false |
| double.Parse / double.TryParse | For decimal numbers | double price = double.Parse(“99.99”); | Yes / No |
| decimal.Parse / decimal.TryParse | For money (exact) | decimal salary = decimal.Parse(“75000.50”); | Yes / No |
Best practice in 2026: Always use TryParse when getting input from users – it prevents your program from crashing if the user types something wrong!
4. Real Examples – Safe Input with TryParse
Bad way (will crash if user types letters):
|
0 1 2 3 4 5 6 7 |
Console.Write("Enter your age: "); int age = int.Parse(Console.ReadLine()); // Crash if user types "twenty" |
Good & safe way (recommended):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Console.Write("Enter your age: "); string input = Console.ReadLine(); if (int.TryParse(input, out int age)) { Console.WriteLine($"You are {age} years old. Nice! 🎉"); } else { Console.WriteLine("Sorry, that's not a valid number. Please try again."); } |
Even better – Keep asking until valid input:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
int age; while (true) { Console.Write("Enter your age: "); string input = Console.ReadLine(); if (int.TryParse(input, out age) && age >= 0 && age <= 120) { break; // Valid! Exit loop } else { Console.WriteLine("Please enter a valid age between 0 and 120."); } } Console.WriteLine($"Great! You're {age} years young! 😊"); |
5. Other Useful Input Methods
- Console.ReadKey() – Read one single key without pressing Enter
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Console.Write("Press Y to continue, any other key to exit: "); var key = Console.ReadKey(true).Key; // true = don't show the key if (key == ConsoleKey.Y) { Console.WriteLine("\nContinuing..."); } else { Console.WriteLine("\nGoodbye!"); } |
- Console.Read() – Read one character (rarely used)
Mini-Project: Smart Calculator (With Safe Input)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
Console.WriteLine("=== Smart Calculator ===\n"); double num1, num2; while (true) { Console.Write("Enter first number: "); if (double.TryParse(Console.ReadLine(), out num1)) break; Console.WriteLine("Invalid number! Try again."); } while (true) { Console.Write("Enter second number: "); if (double.TryParse(Console.ReadLine(), out num2)) break; Console.WriteLine("Invalid number! Try again."); } Console.WriteLine("\nChoose operation:"); Console.WriteLine("1) Add (+) 2) Subtract (-) 3) Multiply (*) 4) Divide (/)"); string choice = Console.ReadLine(); double result = 0; bool valid = true; switch (choice) { case "1": result = num1 + num2; break; case "2": result = num1 - num2; break; case "3": result = num1 * num2; break; case "4": if (num2 == 0) { Console.WriteLine("Cannot divide by zero!"); valid = false; } else { result = num1 / num2; } break; default: Console.WriteLine("Invalid choice!"); valid = false; break; } if (valid) { Console.WriteLine($"\nResult: {num1} {choice switch { "1" => "+", "2" => "-", "3" => "*", "4" => "/" }} {num2} = {result:F2}"); } Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); |
Quick Cheat Sheet – Input & Output
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Output Console.WriteLine("Hello {0}!", name); Console.WriteLine($"Hello {name}!"); // Safe input if (int.TryParse(Console.ReadLine(), out int number)) { // success } else { // show error } // One key var key = Console.ReadKey(true).Key; |
Your Homework (Super Practical!)
- Create a new console project called UserInputMaster
- Make a Personal Info Collector program that:
- Asks for name (string)
- Asks for age (int – safe with TryParse, keep asking until valid)
- Asks for height in cm (double – safe)
- Asks for favorite color (string)
- Prints a beautiful summary card
- Bonus: Add yes/no confirmation at the end using Console.ReadKey()
Next lesson: Exception Handling – we’re going to make your programs bulletproof against crashes!
You’re doing absolutely fantastic! 🎉 Any part confusing? Want more examples with TryParse or formatting? Just tell me — I’m right here for you! 💙
