How can I get the number of items defined in an enum?
I've run a benchmark today and came up with interesting result. Among these three:
var count1 = typeof(TestEnum).GetFields().Length;
var count2 = Enum.GetNames(typeof(TestEnum)).Length;
var count3 = Enum.GetValues(typeof(TestEnum)).Length;
GetNames(enum) is by far the fastest!
| Method | Mean | Error | StdDev |
|--------------- |---------- |--------- |--------- |
| DeclaredFields | 94.12 ns | 0.878 ns | 0.778 ns |
| GetNames | 47.15 ns | 0.554 ns | 0.491 ns |
| GetValues | 671.30 ns | 5.667 ns | 4.732 ns |