Small Tip: Getting the name of the current or calling method at runtime for debugging

My blog has moved. You can view this post at the following address: http://www.osherove.com/blog/2006/5/14/small-tip-getting-the-name-of-the-current-or-calling-method.html
Published Monday, May 15, 2006 1:05 AM by RoyOsherove
Filed under: ,

Comments

Sunday, May 14, 2006 7:26 PM by Wallym

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Nice info. Thanks Roy!
Monday, May 15, 2006 1:48 AM by Mihir Solanki

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Excellent ...
Monday, May 15, 2006 2:45 AM by Hermann Klinke

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

You could also just use MethodBase.GetCurrentMethod(). This returns the MethodInfo of the currently executing method. Both classes are in the System.Reflection namespace.
Monday, May 15, 2006 2:46 AM by Hermann Klinke

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Ooops. Sorry, I did not read your post entirely ;-). You can delete my comment.
Monday, May 15, 2006 1:30 PM by Imran Koradia

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Any sort of overhead that one should be concerned about when using either of these techniques (StackTrace or MethodBase) considering that the tracing code would actually be part of the production code? Both the techniques are indeed very useful to log trace statements but when we're speaking of thousands of users, would the method calls have any effect on performance whatsoever (compared to just sticking in string constants)?

Thanks!
Monday, May 15, 2006 1:44 PM by Roy Osherove

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Imran. There is a perf impact compared to strings, but I wouldn't count this out before I did some perf testing. Try adding some of that code to your real application and *measure*.
I'm not a big fan of premature optimization, and I only optimize for speed when I find out that I need to.
So - Id run tests with and without this code and check the perf difference.
Most likely it will be negligible. If it doesn't - You can always use hard coded string in the places where the perf hit is the biggest and use the easier method listed here for places with less overhead.
Tuesday, May 16, 2006 9:54 AM by David M. Kean

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

You probably don't want to catch Exception, if the JIT fails to JIT a method, or if an assembly is missing or a attribute's constructors throws an exception you are going to catch and handle these exactly the same; by ignoring them. Not real good practice.