Search code examples
c#reflectionnameofcallermembername

Should I provide a method with a member name with nameof, or should I depend on CallerMemberName to do it for me?


How is CallerMemberName implemented?

I get what it does - it allows us to keep magic strings out of our code - but should it be used over nameof and what is more performant?

Whats the difference/how does CallerMemberName exactly work?


Solution

  • CallerMemberName is a compile time trick to place the name of the current member in the call to another method. nameof is also a compile time trick to do something similar: it takes the string representation of a member.

    Which to use is up to you. I would say: use CallerMemberName where you can, and nameof where you must. CallerMemberName is even more automated than nameof, so that is why I prefer that one.

    Both have the same performance implication: only on compile time it takes some extra time to evaluate the code, but that is neglectable.