C#•Input/Output
C# Console Input and Output: Console.WriteLine and ReadLine
Learn Console.WriteLine, Console.ReadLine, string parsing, and formatting flags.
Syntax
Console.WriteLine($"Message: {var}");
string input = Console.ReadLine();
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| Console.WriteLine | Method | Prints string followed by newline. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
public class Program {
public static void Main() {
string service = "Compilra Engine";
int requestsPerSec = 4500;
double p99LatencyMs = 4.25;
// Structured console output
Console.WriteLine("=== Service Diagnostics ===");
Console.WriteLine($"Service: {service}");
Console.WriteLine($"Throughput: {requestsPerSec:N0} req/s");
Console.WriteLine($"P99 Latency: {p99LatencyMs:F2} ms");
}
}Expected Output:
=== Service Diagnostics === Service: Compilra Engine Throughput: 4,500 req/s P99 Latency: 4.25 ms
How It Works: Step-by-Step
- Lines 5-7: Defines diagnostic parameters.
- Lines 10-13: {requestsPerSec:N0} formats integers with comma separators.
Key Concepts
- Console.WriteLine handles output formatting cleanly.
- :N0 format adds comma thousand-separators.
- :F2 formats numbers with 2 fixed decimal places.
Common Mistake: Not handling null when reading from Console.ReadLine()
Console.ReadLine() returns null at EOF. Always handle potential nulls.
❌ Incorrect
int age = int.Parse(Console.ReadLine()); // Crashes if input is null!
✅ Correct
string input = Console.ReadLine();
if (int.TryParse(input, out int age)) { /* Safe */ }Related C# Tutorials & Compiler
C# Stdin Input: Reading Lines Until EOF with Console.ReadLine()
Loop over pre-supplied stdin lines until EOF with Console.ReadLine() != null and parse invariant decimal amounts reliably in Mono 6.6.
C# Strongly Typed Implicit Var Assignments and Data Types
Master C# static typing with implicit var inference, primitive types (int, double, decimal, bool), and formatting specifiers.
C# String Methods, String Interpolation, and StringBuilder
Master text manipulation with string methods, raw string literals, and StringBuilder.
C# Type Casting: int.TryParse, as, and is Pattern Matching
Safely parse strings and cast objects using int.TryParse, as operator, and is pattern matching.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.