404 Not Found

404 Not Found


nginx

Input and Output

Console.Write and Console.WriteLine

Console.Write outputs text without a trailing newline, while Console.WriteLine appends a newline automatically.

Example

CSHARP
Console.Write("Hello");
Console.Write(" ");
Console.WriteLine("World");
Console.WriteLine("Second line");
▶ Try it Yourself
TEXT
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

CSHARP
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);
▶ Try it Yourself
TEXT
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

CSHARP
string name = "Bob";
int age = 30;
Console.WriteLine($"Name: {name}, Age: {age}");
int x = 10, y = 20;
Console.WriteLine($"Result: {x + y}");
▶ Try it Yourself
TEXT
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

CSHARP
Console.WriteLine("|{0,10}|", "Right");
Console.WriteLine("|{0,-10}|", "Left");
Console.WriteLine($"|{"InterpR",10}|");
Console.WriteLine($"|{"InterpL",-10}|");
▶ Try it Yourself
TEXT
|     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

CSHARP
double pi = 3.14159265;
Console.WriteLine("{0:F2}", pi);
Console.WriteLine("{0:F4}", pi);
Console.WriteLine($"{pi:F3}");
▶ Try it Yourself
TEXT
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

CSHARP
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}");
▶ Try it Yourself
TEXT
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

CSHARP
Console.WriteLine("Please enter your name:");
string input = Console.ReadLine();
Console.WriteLine($"Hello, {input}!");
▶ Try it Yourself
TEXT
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

CSHARP
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}");
▶ Try it Yourself
TEXT
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

CSHARP
Console.WriteLine("Press any key to continue...");
ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine();
Console.WriteLine($"You pressed: {key.KeyChar}");
▶ Try it Yourself
TEXT
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

CSHARP
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}");
▶ Try it Yourself
TEXT
Unit price: ¤29.90, Quantity: 3, Total: ¤89.70
|    ¤29.90|
Hexadecimal: 00FF

Formatting Best Practices

Example

CSHARP
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");
}
▶ Try it Yourself
TEXT
    Item    Price   Stock
------------------------
   Apple     5.50     120
  Banana     3.20      85
  Orange     4.80     200

Enter quantity to purchase:
5
Total: ¤27.50

❓ FAQ

Q What is the difference between int.Parse and int.TryParse?
A Parse throws an exception on failure, while TryParse returns a bool without throwing. Prefer TryParse.
Q How do you output literal braces in string interpolation?
A Use double braces to escape: {{ outputs {, and }} outputs }.
Q When does Console.ReadLine return null?
A It returns null when the input stream has reached its end, which rarely occurs in an interactive console.
Q Why does the currency symbol display as ¤?
A ¤ is the culture-invariant currency symbol. Setting the system locale or specifying culture info will display the appropriate currency symbol.

📖 Summary

📝 Exercises

  1. Write a program that uses string interpolation to output a personal info card with name, age, and height, with each field aligned
  2. Write a simple calculator: read two integers and an operator, output the result, and use TryParse to handle input
  3. 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
  4. Write a program that reads an integer and outputs it in decimal (D8), hexadecimal (X), and percent (P) formats
  5. Write a program that uses Console.ReadKey for menu selection: press 1 to show the time, press 2 to exit
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏