ภาพรวม
ใน C# ไม่สามารถใช้ const กับอาร์เรย์ได้ เพราะอาร์เรย์เป็น reference type และ const ต้องเป็น compile-time constant ใช้ readonly หรือ ReadOnlyCollection<T> แทน
วิธีที่ 1: static readonly (แนะนำสำหรับ Array)
public static class Constants {
// สามารถกำหนดค่าได้ที่ runtime (ใน constructor หรือ field initializer)
public static readonly string[] Vehicles = { "Car", "Motorbike", "Cab" };
public static readonly int[] Numbers = { 1, 2, 3, 4, 5 };
}
คุณสมบัติ
- กำหนดค่าได้ครั้งเดียว (ที่ declaration หรือใน static constructor)
- อาร์เรย์ตัวเองไม่สามารถเปลี่ยน reference ได้ แต่องค์ประกอบภายในเปลี่ยนได้!
- ต้องระวัง:
Constants.Vehicles[0] = "Truck";ยังทำได้
วิธีที่ 2: ReadOnlyCollection<T> (Immutable จริง)
using System.Collections.ObjectModel;
public static class Constants {
public static readonly ReadOnlyCollection<string> Vehicles =
new ReadOnlyCollection<string>(new[] { "Car", "Motorbike", "Cab" });
}
C# 6+ (Expression-bodied + initializer)
public static class Constants {
public static ReadOnlyCollection<string> Vehicles { get; } =
new ReadOnlyCollection<string>(new[] { "Car", "Motorbike", "Cab" });
}
วิธีที่ 3: ImmutableArray (จาก System.Collections.Immutable)
using System.Collections.Immutable;
public static class Constants {
public static readonly ImmutableArray<string> Vehicles =
ImmutableArray.Create("Car", "Motorbike", "Cab");
}
เปรียบเทียบ
| วิธี | Immutable Reference | Immutable Elements | Performance |
|---|---|---|---|
| static readonly T[] | ได้ | ไม่ได้ (แก้ไข element ได้) | เร็วที่สุด |
| ReadOnlyCollection<T> | ได้ | ได้ (wrapper) | มี overhead เล็กน้อย |
| ImmutableArray<T> | ได้ | ได้ (struct, คัดลอกเมื่อแก้ไข) | ดี สำหรับ immutable patterns |
Best Practice
- ใช้
static readonly T[]สำหรับ internal use ที่ไว้วางใจโค้ดไม่แก้ไข element - ใช้
ReadOnlyCollection<T>หรือImmutableArray<T>สำหรับ public API - หลีกเลี่ยงการ return array โดยตรงจาก public property (defensive copy)