Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

@ หน้า String ใน C# (Verbatim String) คืออะไร

@ (Verbatim Identifier) คืออะไร?

Prefix @ หน้า String Literal ทำให้เป็น Verbatim String - Compiler จะอ่าน String "ตรงตัว" ไม่ประมวลผล Escape Sequences

คุณสมบัติหลัก

  • Ignore Escape Sequences: \n, \t, \\, \" → เป็นตัวอักษรตรงตัว
  • รองรับ Multi-line String (Line Breaks ตรงๆ)
  • Double Quote ภายใน: เขียน "" (Double Double Quote)
  • Path/File ใช้งานง่าย: @"C:\Path\File.txt" แทน "C:\\Path\\File.txt"

ตัวอย่างเปรียบเทียบ


using System;

class Program
{
    static void Main()
    {
        // Normal String - Process Escapes
        Console.WriteLine("Line 1\nLine 2\tTab");
        // Output:
        // Line 1
        // Line 2    Tab
        
        // Verbatim String - Literal
        Console.WriteLine(@"Line 1\nLine 2\tTab");
        // Output:
        // Line 1\nLine 2\tTab
        
        // Multi-line
        string multi = @"Line 1
Line 2
Line 3";
        Console.WriteLine(multi);
        
        // Quote ใน String
        string quote = @"He said ""Hello""";
        Console.WriteLine(quote); // He said "Hello"
        
        // File Path - ใช้งานง่ายที่สุด
        string path1 = @"C:\Users\John\Documents\file.txt";
        string path2 = "C:\\Users\\John\\Documents\\file.txt"; // ทั้งคู่เท่ากัน
        
        Console.ReadLine();
    }
}

Output

Line 1
Line 2    Tab
Line 1\nLine 2\tTab
Line 1
Line 2
Line 3
He said "Hello"

Interpolated Verbatim String (C# 6+)


var name = "John";
var path = $@"C:\Users\{name}\Documents"; // Combine @ and $
Console.WriteLine(path); // C:\Users\John\Documents

// Multi-line Interpolated
var sql = $@"
SELECT * 
FROM Users 
WHERE Name = '{name}'
  AND Active = 1
";

Raw String Literals (C# 11+) - ทันสมัยกว่า @


// Single-line
string s1 = """Hello "World" """;

// Multi-line (Indent ตาม Closing """)
string s2 = """
    SELECT * 
    FROM Users 
    WHERE Name = 'John'
    """;

// Interpolated Raw String (จำนวน $ กำหนด { count)
var name = "John";
string s3 = $"""
    Hello {name}!
    """;

string s4 = $$"""
    Hello {{name}}! // {{ }} = Literal Braces
    {name}           // { } = Interpolation
    """;

สรุปเมื่อไหร่ใช้ @

Scenarioแนะนำ
File Path / Regex Pattern✅ @ หรือ Raw String (C# 11+)
Multi-line String (SQL, JSON, HTML)✅ Raw String (C# 11+) ดีกว่า @
String ที่มี Escape Characters เยอะ✅ @
General StringNormal String หรือ $ Interpolation

⚠️ ข้อควรระวัง

  • @ ไม่ทำให้ String เป็น Immutable เพิ่ม (String Immutable อยู่แล้ว)
  • @ เป็นแค่ Compile-time Feature รันไทม์เหมือนกัน
  • ใน Regex ใช้ @ ทำให้ Pattern อ่านง่าย: @"\d{3}-\d{2}-\d{4}"