cleansharp.NET
"Clean code always looks like it was written by someone who cares."— Robert C. Martin (Uncle Bob)
Use nameof(Enum.Member)
instead of Enum.Member.ToString()
for better performance and compile-time evaluation.
Using nameof(Enum.Member)
is evaluated at compile time, unlike Enum.Member.ToString()
which is evaluated at runtime.
This compile-time evaluation improves efficiency and can optimize the performance of your code.
This code uses runtime evaluation, which is less efficient:
string roleName = UserRole.Administrator.ToString(); // "Administrator"
This code uses compile-time evaluation for better performance:
string roleName = nameof(UserRole.Administrator); // "Administrator"
In performance-critical applications, the difference between compile-time and runtime evaluation can be significant.nameof()
provides a more efficient approach to convert enum members to strings, as the string value is determined during compilation rather than at runtime.
However, this compile-time evaluation means you need to ensure all referencing projects are recompiled when enum members change to maintain consistency.
Here’s a concrete performance comparison between the two approaches:
| Method | Mean | Error | StdDev | Gen0 | Allocated |
|------------- |-----------:|----------:|----------:|-------:|----------:|
| EnumToString | 11.0370 ns | 0.2897 ns | 0.4840 ns | 0.0038 | 24 B |
| NameofEnum | 0.1436 ns | 0.0615 ns | 0.0514 ns | - | - |
The benchmark clearly shows that nameof()
is significantly faster (about 77x) and doesn’t allocate any memory on the heap.
nameof(Enum.Member)
is evaluated at compile timeEnum.Member.ToString()