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.

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s