DotNet C# Performance Tip: Use the nameof Operator to Get Enum Names

Abhishek Malaviya
2 min readJul 22, 2024

--

When working with enums in .NET, you often need to get the name of an enum value as a string. A common approach is to use the ToString() method. However, there's a more performant way to achieve this using the nameof operator.

The nameof operator provides several advantages over the ToString() method:

  • Performance: nameof is evaluated at compile time, making it faster at runtime compared to ToString(), which incurs a method call overhead.
  • Compile-time Safety: nameof is checked at compile time, ensuring that any renaming of the enum member is caught by the compiler, reducing the risk of runtime errors.

Example

Consider the following enum:

    public enum Score
{
Low = 0,
Medium = 1,
High =2
}

Benchmark Result

Here you can see that the nameof operator is over 17 times faster compared to ToString(), and it also doesn't allocate any memory.

Conclusion

Using the nameof operator to get the name of an enum value can help improve the performance and maintainability of your .NET applications. It ensures compile-time safety and avoids the overhead of a method call, making your code cleaner and faster.

Thank you for reading! If you found this helpful, please clap to show your support and encourage the writing of more great stories.

--

--

No responses yet