Input and Output
Console.Write and Console.WriteLine
Console.Write outputs text without a trailing newline, while Console.WriteLine appends a newline automatically.
Example
Console.Write("Hello");
Console.Write(" ");
Console.WriteLine("World");
Console.WriteLine("Second line");
Hello World
Second line
Placeholder Formatting
Use {0}, {1}, and so on as placeholders to insert variable values into a string, listing the corresponding arguments in order after the format string.
Example
string name = "Alice";
int age = 25;
Console.WriteLine("Name: {0}, Age: {1}", name, age);
Console.WriteLine("{0} is {1} years old, {0} is a programmer", name, age);
Name: Alice, Age: 25
Alice is 25 years old, Alice is a programmer
String Interpolation
Prefix a string with $ and write variables or expressions directly inside {}. This is more readable than placeholder formatting.
Example
string name = "Bob";
int age = 30;
Console.WriteLine($"Name: {name}, Age: {age}");
int x = 10, y = 20;
Console.WriteLine($"Result: {x + y}");
Name: Bob, Age: 30
Result: 30
Alignment Control
Specify a width with a comma in placeholders or interpolation: positive values right-align, negative values left-align. For example, {0,10} right-aligns with a width of 10, and {0,-10} left-aligns with a width of 10.
Example
Console.WriteLine("|{0,10}|", "Right");
Console.WriteLine("|{0,-10}|", "Left");
Console.WriteLine($"|{"InterpR",10}|");
Console.WriteLine($"|{"InterpL",-10}|");
| Right|
|Left |
| InterpR|
|InterpL |
Precision Control
Use format specifiers to control numeric precision: F2 keeps 2 decimal places, F4 keeps 4 decimal places, and so on.
Example
double pi = 3.14159265;
Console.WriteLine("{0:F2}", pi);
Console.WriteLine("{0:F4}", pi);
Console.WriteLine($"{pi:F3}");
3.14
3.1416
3.142
Common Format Specifiers
| Specifier | Name | Description |
|---|---|---|
C |
Currency | Adds currency symbol |
D |
Decimal | Pads integer with zeros |
F |
Fixed-point | Fixed decimal places |
P |
Percent | Multiplies by 100, adds % |
X |
Hexadecimal | Converts to hexadecimal |
Example
int num = 255;
double money = 1234.56;
double ratio = 0.856;
Console.WriteLine($"Currency: {money:C}");
Console.WriteLine($"Decimal: {num:D6}");
Console.WriteLine($"Fixed-point: {money:F1}");
Console.WriteLine($"Percent: {ratio:P1}");
Console.WriteLine($"Hexadecimal: {num:X}");
Currency: ¤1,234.56
Decimal: 000255
Fixed-point: 1234.6
Percent: 85.6%
Hexadecimal: FF
Console.ReadLine for Input
Console.ReadLine() reads a line of text from the console and returns it as a string. It returns null when the end of the input stream is reached.
Example
Console.WriteLine("Please enter your name:");
string input = Console.ReadLine();
Console.WriteLine($"Hello, {input}!");
Please enter your name:
Charlie
Hello, Charlie!
Converting Numeric Input
Since Console.ReadLine() returns a string, use int.Parse, int.TryParse, or Convert.ToInt32 to convert it to a number.
Example
string str1 = "42";
int num1 = int.Parse(str1);
int num2 = Convert.ToInt32(str1);
string str2 = "abc";
if (int.TryParse(str2, out int result))
{
Console.WriteLine($"Conversion succeeded: {result}");
}
else
{
Console.WriteLine("Conversion failed, input is not a valid integer");
}
Console.WriteLine($"Parse result: {num1}");
Console.WriteLine($"Convert result: {num2}");
Conversion failed, input is not a valid integer
Parse result: 42
Convert result: 42
Console.ReadKey for Single Key Input
Console.ReadKey() reads a single keypress without requiring Enter. It returns a ConsoleKeyInfo object, and the character can be accessed via KeyChar.
Example
Console.WriteLine("Press any key to continue...");
ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine();
Console.WriteLine($"You pressed: {key.KeyChar}");
Press any key to continue...
A
You pressed: A
Expressions and Formatting in Interpolation
You can write expressions inside interpolation {}, and also combine format specifiers with alignment. The syntax is {expression,alignment:formatSpecifier}.
Example
double price = 29.9;
int quantity = 3;
Console.WriteLine($"Unit price: {price:C}, Quantity: {quantity}, Total: {price * quantity:C}");
Console.WriteLine($"|{price,10:C}|");
int hex = 255;
Console.WriteLine($"Hexadecimal: {hex:X4}");
Unit price: ¤29.90, Quantity: 3, Total: ¤89.70
| ¤29.90|
Hexadecimal: 00FF
Formatting Best Practices
- Prefer string interpolation
$""for clearer, more readable code - Always use
TryParseinstead ofParsefor user input to avoid exceptions - Use consistent alignment widths when outputting tabular data
- Use the
Cformat specifier for currency amounts andPfor percentages - Extract complex formatting into methods to reduce duplication
- Use
ReadKeyto pause the program, andReadLineto read a full line of input
Example
string[] names = { "Apple", "Banana", "Orange" };
double[] prices = { 5.5, 3.2, 4.8 };
int[] stocks = { 120, 85, 200 };
Console.WriteLine($"{"Item",8}{"Price",8:C}{"Stock",8}");
Console.WriteLine(new string('-', 24));
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine($"{names[i],8}{prices[i],8:F2}{stocks[i],8}");
}
Console.WriteLine("\nEnter quantity to purchase:");
if (int.TryParse(Console.ReadLine(), out int qty) && qty > 0)
{
double total = prices[0] * qty;
Console.WriteLine($"Total: {total:C}");
}
else
{
Console.WriteLine("Invalid input, please enter a positive integer");
}
Item Price Stock
------------------------
Apple 5.50 120
Banana 3.20 85
Orange 4.80 200
Enter quantity to purchase:
5
Total: ¤27.50
❓ FAQ
{{ outputs {, and }} outputs }.📖 Summary
- Console.Write does not add a newline; WriteLine does
- Placeholder
{0}and interpolation$"{var}"are the two formatting approaches {0,10}right-aligns,{0,-10}left-aligns{0:F2}controls the number of decimal places- Common specifiers: C for currency, D for decimal, F for fixed-point, P for percent, X for hexadecimal
- ReadLine reads a string; use Parse/TryParse/Convert to convert to a number
- ReadKey reads a single key without requiring Enter
- Expressions inside interpolation support combined alignment and formatting
📝 Exercises
- Write a program that uses string interpolation to output a personal info card with name, age, and height, with each field aligned
- Write a simple calculator: read two integers and an operator, output the result, and use TryParse to handle input
- Write a program that outputs 5 products in a table format with name, unit price (F2 format), and stock, using a consistent column width of 10
- Write a program that reads an integer and outputs it in decimal (D8), hexadecimal (X), and percent (P) formats
- Write a program that uses Console.ReadKey for menu selection: press 1 to show the time, press 2 to exit



