See who calls any method in C#

by Mads Kristensen 10. May 2007 06:00

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

Tags: ,

Server-side

Comments

5/11/2007 7:25:39 PM #

Randy Minder

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

Randy Minder United States |

5/11/2007 7:35:51 PM #

Mads Kristensen

Yes, I think so.

Mads Kristensen Denmark |

5/16/2007 2:52:37 AM #

trackback

Trackback from .NET slave

.NET slave |

5/24/2007 11:02:40 PM #

Jeff Jensen

how about:

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

Jeff Jensen United States |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008