Get method name and calling method name in C#

There are times when you need to trace the method call order of your application.   In the System.Diagnostics namespace there is StackTrace.  StackTrace is a collection of StackFrames which provides information about the method calls for the stack call on the current process.

First thing you need to do is add the Diagnostics namespace like so

using System.Diagnostics;

Next in the method you would like to trace add the following:

var stackTrace = new StackTrace(); Console.WriteLine(“Called from {0}”, stackTrace.GetFrame(1).GetMethod().Name); Console.WriteLine(“Entering {0}”, stackTrace.GetFrame(0).GetMethod().Name);

… some code …

Console.WriteLine(“Exiting {0}”, stackTrace.GetFrame(0).GetMethod().Name);

Now when you run it, the first console.writeline will display the method that that call info the method.  the Second and third writeline will display when the method is entered and exited.

Advertisement
This entry was posted in C# and tagged . Bookmark the permalink.