ใช้ Console.WriteLine() แสดงผล ตัวแปรเดียวหรือหลายตัวได้หลายรูปแบบ
1. ตัวแปรเดี่ยว (Single Variable)
int a = 10;
Console.WriteLine("Value: " + a); // String Concatenation
Console.WriteLine("Value: {0}", a); // Composite Formatting
Console.WriteLine($"Value: {a}"); // String Interpolation (C# 6+) — แนะนำ
2. หลายตัวแปร (Multiple Variables)
int a = 10, b = 15, c = 20;
// Composite Formatting
Console.WriteLine("Values: {0}, {1}, {2}", a, b, c);
// String Interpolation (แนะนำ — อ่านง่าย ประสิทธิ์ดี)
Console.WriteLine($"Values: {a}, {b}, {c}");
// Format Specifiers
Console.WriteLine($"Hex: {a:X}, Binary: {Convert.ToString(a, 2)}, Float: {1.5:F2}");
3. Format Specifiers ที่นิยม
| Specifier | คำอธิบาย | ตัวอย่าง |
|---|---|---|
C / c | Currency | 1234.56 → $1,234.56 |
D / d | Decimal (Integer) | 42 → 0042 (D4) |
E / e | Scientific | 1234 → 1.23E+003 |
F / f | Fixed-point | 1.5 → 1.50 (F2) |
N / n | Number with separator | 1000 → 1,000.00 (N2) |
P / p | Percent | 0.25 → 25.00% (P2) |
X / x | Hexadecimal | 255 → FF (X2) |
ตัวอย่างครบถ้วน
using System;
class Program {
static void Main() {
int a = 10, b = 15;
double pi = 3.14159;
decimal price = 1234.56m;
// Single
Console.WriteLine($"Single: a = {a}");
// Multiple
Console.WriteLine($"Multiple: a = {a}, b = {b}");
// With Formatting
Console.WriteLine($"Pi: {pi:F4}"); // 3.1416
Console.WriteLine($"Price: {price:C}"); // $1,234.56
Console.WriteLine($"Hex: {a:X}"); // A
// Conditional Formatting
int positive = 5, negative = -3, zero = 0;
Console.WriteLine($"{positive: +#; -#; 0}"); // +5
Console.WriteLine($"{negative: +#; -#; 0}"); // -3
Console.WriteLine($"{zero: +#; -#; 0}"); // 0
Console.ReadKey();
}
}
Console.Write vs WriteLine
WriteLine: พิมพ์แล้วขึ้นบรรทัดใหม่Write: พิมพ์ต่อเนื่อง ไม่ขึ้นบรรทัดใหม่
สรุป
- ใช้ String Interpolation (
$"") เป็นหลัก — อ่านง่าย เร็ว Type-Safe - ใช้ Composite Formatting (
{0}) เมื่อ Format String มาจาก Config/Resource - ใช้ Format Specifiers สำหรับการจัดรูปแบบตัวเลข วันที่ เงิน