"Clean code always looks like it was written by someone who cares."
— Robert C. Martin (Uncle Bob)

Use nameof(Enum.Member)

✅ One-liner Summary

Use nameof(Enum.Member) instead of Enum.Member.ToString() for better performance and compile-time evaluation.

💡 Short Explanation

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.

🚫 Bad Example

This code uses runtime evaluation, which is less efficient:

string roleName = UserRole.Administrator.ToString(); // "Administrator"

✅ Good Example

This code uses compile-time evaluation for better performance:

string roleName = nameof(UserRole.Administrator); // "Administrator"

💬 Real-World Insight

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.

📊 Benchmark Results

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.

🧠 Key Takeaways

  • nameof(Enum.Member) is evaluated at compile time
  • More efficient than Enum.Member.ToString()
  • Better performance in runtime
  • Requires recompilation of referencing projects when enum members change