คำจำกัดความ
- Constants (ค่าคงที่) - ค่าที่โปรแกรมไม่สามารถเปลี่ยนแปลงได้ระหว่างการทำงาน
- Literals (ค่าคงที่แบบตรง) - คือการเขียนค่าคงที่ "ตรงๆ" ในโค้ด (Syntax Level)
สรุป: Literal คือ "รูปแบบการเขียน" ส่วน Constant คือ "แนวคิด/ความหมาย" - ทุก Literal เป็น Constant แต่ไม่ใช่ทุก Constant เป็น Literal (เช่น Constant ที่คำนวณมาจาก Expression)
ประเภทของ Literals ใน C#
1. Integer Literals (จำนวนเต็ม)
// Decimal (ฐาน 10)
int a = 150;
int b = 300u; // unsigned
long c = 300L; // long
// Hexadecimal (ฐาน 16) - ใช้ Prefix 0x หรือ 0X
int hex1 = 0xFF; // 255
int hex2 = 0x1A3F; // 6719
// Binary (ฐาน 2) - C# 7.0+ ใช้ Prefix 0b หรือ 0B
int bin = 0b1010; // 10
2. Floating-Point Literals (จำนวนจริง)
// Decimal form
double d1 = 3.14159;
float f1 = 2.5F; // ต้องมี F/f ต่อท้าย
decimal dec1 = 123.45M; // ต้องมี M/m ต่อท้าย
// Exponential form
double d2 = 2.35468E-7; // 2.35468 × 10⁻⁷
float f2 = 1.5E+3F; // 1.5 × 10³ = 1500
3. Character Literals (ตัวอักษร)
char c1 = 'A'; // Plain character
char c2 = '\t'; // Escape sequence (Tab)
char c3 = '\n'; // Escape sequence (New line)
char c4 = '\\'; // Escape sequence (Backslash)
char c5 = '\u0041'; // Unicode (UTF-16) - 'A'
char c6 = '\x41'; // Hexadecimal - 'A'
4. String Literals (สตริง)
// Regular string literals
string s1 = "Hello, World";
string s2 = "Path: C:\\Windows"; // Escape backslash
// Verbatim string literals (ด้วย @) - ไม่ต้อง Escape
string s3 = @"Hello, World";
string s4 = @"Path: C:\Windows"; // อ่านง่ายกว่า
string s5 = @"Line 1
Line 2
Line 3"; // Multi-line string
5. Boolean Literals
bool b1 = true;
bool b2 = false;
6. Null Literal
string s = null;
object obj = null;
Constants vs Literals - ตัวอย่างเปรียบเทียบ
| โค้ด | ประเภท | คำอธิบาย |
|---|---|---|
const int MAX = 100; |
Constant (Named Constant) | มีชื่อ ใช้ซ้ำได้ ทั่วโปรแกรม |
int x = 100; |
Literal (Integer Literal) | เขียนค่าตรงๆ ในโค้ด ใช้ครั้งเดียว |
const double PI = 3.14159; |
Constant | Named Constant สำหรับค่า Pi |
double area = 3.14159 * r * r; |
Literal | Magic Number - ไม่ควรทำแบบนี้ |
Best Practice
- ใช้ Named Constants (
constหรือreadonly) แทน Magic Numbers - ตั้งชื่อ Constants เป็น PascalCase (เช่น
MaxConnectionCount) - ใช้
readonlyสำหรับค่าที่กำหนดได้เฉพาะใน Constructor (Runtime Constant) - ใช้
constสำหรับค่าที่ทราบตอน Compile Time (Compile-time Constant)