|
See Who Calls Any Method In C#
By Mads Kristensen
Expert Author
Article Date: 2007-05-16
In some situations it can be important to know which methods are calling other methods.
Think of an error log. Here you would like to know which method that threw the error and at what line in what file.
This helps to debug runtime code and makes it very easy to find the exact point of failure.
C# 2.0 has the possibility to go back in time and inspect which methods called other methods all the way up the stack.
Here is a static method that does just that and returns the caller of any method in the stack.
/// <summary>
/// Retrieves the caller of any method in the stack.
/// </summary>
/// <param name="skipFrames">How many steps to go back up the stack.</param>
/// <returns>The method name, file name and line number of any caller.</returns>
public static string GetCaller(int skipFrames)
{
System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(skipFrames, true);
string method = sf.GetMethod().ToString();
int line = sf.GetFileLineNumber();
string file = sf.GetFileName();
if (file != null)
{
// Converts the absolute path to relative
int index = file.LastIndexOf("\\") + 1;
if (index > -1)
file = file.Substring(index);
}
return method + " in file " + file + " line: " + line;
}
In a error logging scenario you probably want to set the skipFrames parameter to 1, which is the latest method or the method highest on the stack.
Comments
About the Author:
Mads Kristensen currently works as a Senior Developer at Traceworks located
in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in
2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and
web services in his daily work as well. A true .NET developer with great passion for the simple solution.
http://www.madskristensen.dk/
|