Sử dụng Enum.GetNames(typeof(TEnum)) hoặc Enum.GetValues(typeof(TEnum)) để lấy tất cả thành viên, sau đó đếm Length.
Cách 1: Enum.GetNames (Trả về string[])
enum Level { Low, Medium, High }
int count = Enum.GetNames(typeof(Level)).Length; // 3
Console.WriteLine(count);
// Lấy cả tên
foreach (string name in Enum.GetNames(typeof(Level)))
Console.WriteLine(name);
Cách 2: Enum.GetValues (Trả về Array các giá trị enum)
int count = Enum.GetValues(typeof(Level)).Length; // 3
// Lấy giá trị underlying (int)
foreach (Level level in Enum.GetValues(typeof(Level)))
Console.WriteLine($"{(int)level}: {level}");
Kết quả
0: Low
1: Medium
2: High
Enum với giá trị tùy chỉnh
enum HttpStatus
{
Ok = 200,
NotFound = 404,
ServerError = 500
}
int count = Enum.GetNames(typeof(HttpStatus)).Length; // 3
// Giá trị underlying không ảnh hưởng đếm
C# 7.2+: Enum.GetNames<TEnum>() (Generic, type-safe)
// Cần using System.Runtime.CompilerServices (hoặc .NET 5+)
string[] names = Enum.GetNames(); // Compile-time type check
int count = names.Length;
Lấy Dictionary Name -> Value
var dict = Enum.GetValues(typeof(Level))
.Cast()
.ToDictionary(e => e.ToString(), e => (int)e);
// { "Low": 0, "Medium": 1, "High": 2 }
Flags Enum (Bitwise)
[Flags]
enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
All = Read | Write | Execute // 7
}
int count = Enum.GetNames(typeof(Permissions)).Length; // 5 (kể cả None, All)
// Lưu ý: All là combination, không phải distinct flag
Extension Method tiện lợi
public static class EnumExtensions
{
public static int Count() where T : Enum => Enum.GetNames(typeof(T)).Length;
public static string[] GetNames() where T : Enum => Enum.GetNames(typeof(T));
public static T[] GetValues() where T : Enum => (T[])Enum.GetValues(typeof(T));
}
// Usage
int c = EnumExtensions.Count(); // 3
var names = EnumExtensions.GetNames();
Lưu ý
Enum.GetNamesvàGetValuesallocation array mới mỗi lần gọi -> cache nếu gọi nhiều.- Enum underlying type mặc định
int, có thể làbyte,short,long... Enum.IsDefined(typeof(Level), value)kiểm tra giá trị có hợp lệ không.