OK looks like StackFrame will do what I need. Just wondering how slow it will be since I want to use it for logging purposes. Something like:
StartMethod will then log whatever is passed in as the stack frame.
It's not speedy. Heck it's more expensive that throwing exceptions.I'd suggest passing the name in as a string and hoping people use it right.
If you must go this route you don't have to pass it in at all though. Just to this in the logger.
StackTrace stackTrace = new StackTrace(); MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
Slow, but useful if you've wrap it in #if DEBUG ... #endif directive. (DEBUG is automatically defined when building with DEBUG configuration. Can be changed in "Build" tab of Project Properties, via "Define DEBUG constant" checkbox in corresponding build configuration.)
So when you compile without DEBUG, this won't eat away your performance.
The reflection route won't always work, due to inlining. The CallerMemberNameAttribute is more reliable, but it doesn't give you the current method, but rather the calling method. Should still work for what you're trying to do, obviously, but you specifically asked about getting the current method name. I'd also point out that the CallerMemberName approach can be misused, though that's probably not something you're worried about.
Actually, it turns out StackFrame isn't that slow, less than 1 ms. And since I can't use C# 5.0, I'll stick with that for now.
But it is good to know this feature was added to 5.0.
BTW this is all my own code so I have full control over what happens where. However I need this because hand-coding each method is going to take a long time, vs simply copy/pasting the same thing everywhere.
Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.