How Heavy Is the nameof Expression in C#?

With proof, we'll be looking at how heavy (or light!) the C# nameof expression is and what that means for your code.

How Heavy Is the nameof Expression in C#?

Extremely Light!

The nameof expression is evaluated at compile time! If we quote the documentation:

A nameof expression is evaluated at compile time and has no effect at run time.

I always assumed it was reflection based and I would feel guilty using it thinking it would be expensive to call. Turns out it's at constant time, so use it without fear!

We can prove this by looking at what the result of nameof gets compiled to by looking at the following SharpLab.io example:

nameof simply gets compiled to a string.

Where we can see that the result of nameof is simply compiled into a string. No more worrying for me about how it will impact log entries in terms of performance 🥳