#undef ใช้ยกเลิก (Undefine) Symbol ที่เคย Define ไว้ ทำให้ #if SYMBOL เงื่อนไขเป็น False
Syntax
#undef SYMBOL_NAME
ตัวอย่าง
#define ONE
#undef TWO
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
#if (ONE && TWO)
Console.WriteLine("Both are defined");
#elif (ONE && !TWO)
Console.WriteLine("ONE is defined and TWO is undefined");
#elif (!ONE && TWO)
Console.WriteLine("ONE is undefined and TWO is defined");
#else
Console.WriteLine("Both are undefined");
#endif
}
}
}
ผลลัพธ์
ONE is defined and TWO is undefined
คำอธิบาย
#define ONE- กำหนด Symbol ONE = True#undef TWO- ยกเลิก Symbol TWO (แม้จะไม่เคย Define ก็ได้)#if (ONE && !TWO)- True AND True = True → Execute Branch นี้
การใช้งานจริง
// ปิด Feature ชั่วคราว
#define EXPERIMENTAL_FEATURE
// #undef EXPERIMENTAL_FEATURE // Uncomment เพื่อปิด
#if EXPERIMENTAL_FEATURE
EnableNewUI();
#endif
// ป้องกันการ Define ซ้ำ
#if !MY_SYMBOL
#define MY_SYMBOL
#endif
ข้อจำกัด
- ต้องอยู่บนสุดไฟล์ (ก่อน Code ใดๆ)
- Scope แค่ไฟล์เดียว (File-level)
- ไม่ใช่ Variable - ไม่มีค่า ใช้แค่ True/False สำหรับ #if