Console Input & Output in C#
Use Console.WriteLine, Console.Write, Console.ReadLine, formatted output with string interpolation, and composite formatting.
Console Output Basics
1. Console.WriteLine() (Print with Newline)
`Console.WriteLine()` prints a value followed by a newline. Each call prints on a new line.
2. Console.Write() (Print Without Newline)
`Console.Write()` prints without adding a newline — the next output continues on the same line.
3. Printing Variables (String Interpolation)
Use `$"..."` string interpolation to embed variables directly in a string — the cleanest way to print variables in C#.
4. Console.Error (Writing to stderr)
`Console.Error.WriteLine()` writes to the standard error stream — useful for logging errors separately from normal output.
Formatted Console Output
1. Format Specifiers
Use format specifiers inside `{}` to control number formatting — currency, fixed decimals, percentages, and padding.
2. Print a Simple Table (Aligned Columns)
Use `PadRight()` and `PadLeft()` to align columns and print a formatted table.
3. Composite Formatting (string.Format)
`string.Format()` uses `{0}`, `{1}` placeholders — the older formatting style, still common in logs and legacy code.
Console Input (Reading User Data)
1. Console.ReadLine() (Interactive Input)
`Console.ReadLine()` waits for the user to type a line and press Enter. It always returns a `string?`.
2. Reading a Number
Read a number safely using `int.TryParse()` to avoid exceptions on invalid input.
3. Command-Line Arguments (args[])
Access arguments passed when running the program via `args[]` in the top-level program or `string[] args` in `Main`.
4. Scan Multiple Numbers (Space Separated)
Read a line of space-separated numbers, split it, and parse each value.