@ Prefix (Verbatim String Literal) ทำให้ String ไม่ต้อง Escape Special Characters และรองรับ Multi-line
1. ไม่ต้อง Escape Backslash
// ปกติ - ต้อง Escape string path1 = "D:\\New\\Folder\\File.txt"; // @ Prefix - เขียนตรงๆ string path2 = @"D:\New\Folder\File.txt";
2. Multi-line String
using System;
namespace Demo
{
class Program
{
static void Main()
{
string message = @"Welcome User,
Kindly wait for the image to
load";
Console.WriteLine(message);
}
}
}
ผลลัพธ์
Welcome User, Kindly wait for the image to load
3. Escape Double Quote ด้วย Double Double Quote
string quote = @"He said, ""Hello!"""; // He said, "Hello!"
4. Interpolated Verbatim String (C# 6+)
string name = "John";
string path = $@"C:\Users\{name}\Documents"; // เขียน Path ง่ายขึ้น
Raw String Literals (C# 11+)
// ใช้ Triple Quotes - ไม่ต้อง Escape อะไรเลย
string json = """
{
"name": "John",
"age": 30
}
""";
สรุป
| ประเภท | Syntax | Escape | Multi-line |
|---|---|---|---|
| Regular | "..." | ต้อง Escape | ไม่ได้ |
| Verbatim | @"..." | ไม่ต้อง (ยกเว้น "") | ได้ |
| Raw (C# 11+) | """...""" | ไม่ต้องเลย | ได้ |