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

#if DEBUG ใน C# คืออะไร และวิธีใช้งาน

Debug vs Release Mode

ใน Visual Studio มี 2 Build Configuration:

  • Debug Mode: ใช้สำหรับ Debug ทีละบรรทัด ไม่ Optimize โค้ด มี Symbolic Debug Info ครบ
  • Release Mode: ใช้สำหรับ Build Production Optimize โค้ดเต็มที่ ไม่มี Debug Info

#if DEBUG คืออะไร?

Preprocessor Directive ที่ทำให้โค้ดภายในบล็อกทำงาน เฉพาะตอน Build แบบ Debug เท่านั้น

  • ถ้า Build แบบ Debug → #if DEBUG เป็น True → โค้ดรัน
  • ถ้า Build แบบ Release → #if DEBUG เป็น False → โค้ดไม่รัน (ถูกตัดออกตอน Compile)

วิธีเปลี่ยน Build Configuration

  1. เมนู Build → Configuration Manager → เลือก Debug หรือ Release
  2. หรือ Toolbar → Dropdown Solution Configurations → เลือก Debug/Release

ตัวอย่างการใช้งาน

class Program
{
    static void Main()
    {
#if DEBUG
        Console.WriteLine("You are in Debug mode");
        // Log รายละเอียด, ตรวจสอบค่า Variable, เขียนไฟล์ Debug Log
#endif
        Console.WriteLine("โปรแกรมทำงานปกติ");
        Console.ReadKey();
    }
}

กรณีใช้งานจริง

  • Logging ข้อมูล Debug ที่ละเอียด
  • เชื่อมต่อ Database ทดสอบ (Test DB)
  • Skip การ Validate บางอย่างตอน Development
  • แสดงข้อความ Error แบบ Verbose

Compile-time Constants อื่นๆ

#if RELEASE
    // โค้ดสำหรับ Release เท่านั้น
#endif

#define MY_SYMBOL
#if MY_SYMBOL
    // โค้ดเมื่อ Define MY_SYMBOL
#endif