6

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?

J. Lennon
  • 3,311
  • 4
  • 33
  • 64
  • 1
    What do you need to use them for? If they are for reporting stack trace information during an exception, performance should be somewhat irrelevant. If you are using them to instrument the entire application, that is another story altogether. – competent_tech Jul 13 '13 at 01:41
  • 1
    They're compiled in: ["Caller Info values are emitted as literals into the Intermediate Language (IL) at compile time."](http://msdn.microsoft.com/en-us/library/hh534540.aspx) EDIT: Performance wise, I've never benchmarked or used them heavily, but I would suspect that it should be fairly minimal since most of the work is done at compile time. (not sure about performance-critical or super-duper-frequently hit code though) Using reflection based methods (like `StackTrace` or `MethodBase.GetCurrentMethod()`) can be susceptible to method in-lining or obfuscation. – Chris Sinclair Jul 13 '13 at 01:47

1 Answers1

11

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.

Evgeniy Berezovsky
  • 18,571
  • 13
  • 82
  • 156