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

Enum (Enumeration) ใน C#: พื้นฐาน

Enum (Enumeration) ใน C# เป็น Value Type ที่ใช้จัดกลุ่มค่าคงที่ที่มีชื่อ (Named Constants) ใช้แทน Magic Numbers ทำให้โค้ดอ่านง่ายและปลอดภัยกว่า

การประกาศ Enum พื้นฐาน

public enum Vehicle
{
    Car,   // 0
    Bus,   // 1
    Truck  // 2
}

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

using System;

public class Demo
{
    public enum Vehicle
    {
        Car,
        Bus,
        Truck
    }
    
    public static void Main()
    {
        // แปลงเป็นค่าตัวเลข
        int a = (int)Vehicle.Car;   // 0
        int b = (int)Vehicle.Bus;   // 1
        int c = (int)Vehicle.Truck; // 2
        
        Console.WriteLine($"Car = {a}");
        Console.WriteLine($"Bus = {b}");
        Console.WriteLine($"Truck = {c}");
        
        // ใช้งาน
        Vehicle myVehicle = Vehicle.Bus;
        Console.WriteLine($"My vehicle: {myVehicle}"); // แสดงชื่อ "Bus"
    }
}

ผลลัพธ์

Car = 0
Bus = 1
Truck = 2
My vehicle: Bus

คุณสมบัติสำคัญ

  • Strongly Typed: ไม่สามารถมอบหมายค่าผิดประเภทได้ (Compile-time safety)
  • ค่าเริ่มต้น: เริ่มจาก 0 เพิ่มทีละ 1
  • Underlying Type: Default เป็น int เปลี่ยนได้: enum MyEnum : byte { ... }
  • Flags Attribute: ใช้สำหรับ Bitwise Flags [Flags] enum Days { Mon=1, Tue=2, Wed=4 }

เมธอดยอดนิยมของ Enum

  • Enum.GetNames(typeof(T)) - ชื่อทั้งหมด
  • Enum.GetValues(typeof(T)) - ค่าทั้งหมด
  • Enum.IsDefined(typeof(T), value) - ตรวจสอบว่ามีค่านี้หรือไม่
  • Enum.Parse<T>(string) - แปลง String เป็น Enum
  • Enum.TryParse<T>(string, out T) - Parse แบบปลอดภัย

แนวทางปฏิบัติ: ใช้ Enum แทน const int หรือ string literal เพื่อ Type Safety และ IDE IntelliSense