Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 470
J. Lennon Avatar asked Jul 13 '13 01:07

J. Lennon


1 Answers

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.

like image 90
Evgeniy Berezovsky Avatar answered Sep 22 '22 12:09

Evgeniy Berezovsky