Sometimes it’s handy to see the order in which methods are firing, or how long they’re taking, without having to attach a debugger. Typically, you might write some code like this:
This of course gets tedious after a while. There are all kinds of things wrong with this approach. It isn’t DRY. It includes magic strings. You’d almost never need it if you were following TDD. Etc. If you really need this kind of logging detail on a lot of methods, I’d encourage you to investigate AOP options like PostSharp. However, if you’re not quite ready for that but do want to at least eliminate the magic strings from the above code, you can use this little helper to get the type and name of the method for your logging purposes:
Drop that into the class you’re working in, and replace your calls with a call to LogMethod(). Naturally if you need to record both entering and existing of each method, you can adjust to something like this:
For obvious reasons you should avoid leaving these in your production code. One easy way to ensure this is the use of the Conditional attribute. By adding this attribute and specifying DEBUG you can ensure these methods are not even included in your DLLs when you perform a Release build. Here’s an example showing this attribute in use:
Naturally if you’re going to be using this in many classes, you can add it to a common helper class. Note that if you decide to refactor out the duplication in the above Start/End methods, you’ll most likely need to adjust the hard-coded GetFrame(1) to use a higher number, since you’ll need to unwind the stack further to get to the method you’re actually interested in (most likely just incrementing it to 2 will do the trick, assuming you only create one more method).