by via .NET Slave on 5/10/2007 12:00:00 AM
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.
Original Post: See who calls any method in C#
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.