ลิเทอรัลสตริง (String Literals) ใน C#
ลิเทอรัลสตริงหรือค่าคงที่สตริง จะถูกล้อมรอบด้วยเครื่องหมายคำพูดคู่ "" หรือใช้เครื่องหมาย @"" สำหรับ verbatim string (สตริงที่อ่านค่าตรงตัว ไม่ประมวลผล Escape sequence)
ตัวอย่างลิเทอรัลสตริง
"Hello, World"
@"Welcome,
Hope you are doing great!"
ตัวอย่างโค้ด
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
// สตริงทั่วไป
string str1 = "Hello, World";
Console.WriteLine(str1);
// Verbatim string (หลายบรรทัด ไม่ต้อง escape)
string str2 = @"Welcome,
Hope you are doing great!";
Console.WriteLine(str2);
}
}
}
ผลลัพธ์
Hello, World
Welcome,
Hope you are doing great!
Escape Sequences ที่พบบ่อย
| Escape Sequence | ความหมาย |
|---|---|
\n | New line (บรรทัดใหม่) |
\t | Tab |
\\ | Backslash |
\" | เครื่องหมายคำพูดคู่ |
\' | เครื่องหมายคำพูดเดี่ยว |
Verbatim String (@"")
- ไม่ประมวลผล Escape sequence (ยกเว้น
""สำหรับคำพูดคู่ภายใน) - เหมาะสำหรับพาธไฟล์ เช่น
@"C:\Users\Name" - สามารถขึ้นบรรทัดใหม่ได้โดยตรงในโค้ด