J. Lennon
J. Lennon

Reputation: 3361

MethodBase.GetCurrentMethod().Name vs [CallerMemberName]

What are the differences and the impact on the code?

What about performance and limitations, what would make a better fit?

The new attributes:
- [CallerFilePathAttribute]
- [CallerMemberName]
- [CallerLineNumber]

Today they are also available in .NET 4 (It easy to develop and seems magic).. Their values are compiled or resolved at runtime?

Upvotes: 6

Views: 4449

Answers (1)

Evgeniy Berezovsky
Evgeniy Berezovsky

Reputation: 19248

For one, MethodBase.GetCurrentMethod() returns the current method, whereas you can use [CallerMemberName] etc. to pass in the some information about the calling method into the current method.

The former is evaluated at run time using reflection, thus relatively slow, while the latter is processed at compile time and essentially a no-op performance wise. I've actually verified this in tests. Reflection will cost you in the order of some 20 microseconds each time, which can be quite significant if called often, whereas the [Caller...] attributes don't incur a measurable penalty.

Upvotes: 11

Related Questions