C# không cho phép const cho mảng (reference type). Dùng readonly hoặc ReadOnlyCollection<T>.
Cách 1: readonly field (khuyến nghị)
public static readonly string[] Colors = { "Red", "Green", "Blue" };
// Khởi tạo tại runtime (constructor)
public class Config
{
public static readonly string[] AllowedExtensions;
static Config()
{
AllowedExtensions = LoadFromConfig(); // Có thể gán tại runtime
}
}
Cách 2: ReadOnlyCollection<T> (bảo vệ nội dung)
using System.Collections.ObjectModel;
public class Settings
{
private static readonly List _items = new List { "A", "B", "C" };
// Property chỉ đọc, trả về wrapper readonly
public static ReadOnlyCollection Items
=> new ReadOnlyCollection(_items);
// C# 6+ expression-bodied property
// public static ReadOnlyCollection Items { get; }
// = new ReadOnlyCollection(new[] { "A", "B", "C" });
}
Cách 3: ImmutableArray (System.Collections.Immutable)
using System.Collections.Immutable; public static readonly ImmutableArrayConstants = ImmutableArray.Create("A", "B", "C");
So sánh
| Cách | Bảo vệ tham chiếu | Bảo vệ nội dung | Khởi tạo runtime |
|---|---|---|---|
| readonly array | Có | Không (vẫn sửa được element) | Có |
| ReadOnlyCollection | Có | Có (interface chỉ đọc) | Có |
| ImmutableArray | Có | Có (struct bất biến) | Có |
Khuyến nghị: Dùng ImmutableArray cho .NET Core/.NET 5+, ReadOnlyCollection cho .NET Framework.