Conditional Pre-processor Directives ใน C#
Pre-processor Directives เริ่มต้นด้วย # ใช้ควบคุมการคอมไพล์ (Conditional Compilation) ไม่ใช่ Statement ปกติ (ไม่มี Semicolon)
Directives หลัก
| Directive | คำอธิบาย |
|---|---|
#define SYMBOL | กำหนด Symbol (Conditional Compilation Symbol) |
#undef SYMBOL | ยกเลิก Symbol |
#if SYMBOL | เริ่มเงื่อนไข (True = Compile code block) |
#elif SYMBOL | Else-if สำหรับ Preprocessor |
#else | Else Block |
#endif | จบเงื่อนไข #if |
#warning TEXT | แสดง Warning ใน Compiler Output |
#error TEXT | แสดง Error หยุด Compilation |
#region/#endregion | จัดกลุ่มโค้ดใน IDE (Collapsible) |
Operators ใน #if
==(Equality),!=(Inequality)&&(AND),||(OR)!(NOT)
ตัวอย่างครบถ้วน
#define DEBUG
#define VC_V10
using System;
public class Demo
{
public static void Main()
{
#if (DEBUG && !VC_V10)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V10)
Console.WriteLine("VC_V10 is defined");
#elif (DEBUG && VC_V10)
Console.WriteLine("DEBUG and VC_V10 are defined");
#else
Console.WriteLine("DEBUG and VC_V10 are not defined");
#endif
Console.ReadKey();
}
}
ผลลัพธ์
DEBUG and VC_V10 are defined
การใช้งานจริง (Real-world)
// 1. Debug Logging
#if DEBUG
Console.WriteLine($"Debug: User {userId} logged in at {DateTime.Now}");
#endif
// 2. Platform-specific Code
#if NETFRAMEWORK
// .NET Framework only code
#elif NETCOREAPP
// .NET Core / .NET 5+ only code
#endif
// 3. Feature Flags
#define ENABLE_NEW_UI
#if ENABLE_NEW_UI
// New UI Code
#else
// Legacy UI Code
#endif
// 4. Prevent Compiler Optimization Removal
#if DEBUG
public void DebugOnlyMethod() { ... }
#endif
Define Symbols ใน Project Settings
แทนที่จะ #define ในโค้ด ให้ตั้งค่าใน Project Properties → Build → Conditional compilation symbols (เช่น DEBUG;TRACE;MY_FEATURE)