See who calls any method in C#
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.