See who calls any method in C#

May 9, 2007

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.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (3) -

Randy Minder
Randy Minder United States
5/11/2007 10:25:39 AM #

I believe this only works if you are creating debug version of assemblies, correct? Otherwise, you don't have access to line numbers.

Mads Kristensen
Mads Kristensen Denmark
5/11/2007 10:35:51 AM #

Yes, I think so.

Jeff Jensen
Jeff Jensen United States
5/24/2007 2:02:40 PM #

how about:

return String.Format("method {0} in file {1} line {2}",method ,file ,line);

Pingbacks and trackbacks (1)+

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.