Monday, December 01, 2008 6:04 AM
kolbis
Who Called Me?
Sometimes it is important to understand who called a given method.
I have used it for logging purposes.
Microsoft had used it, for example the Visual Studio Team Profiler, where there is the Caller/Callee View:
Ever wondered how they do it?
My Solution
As I mentioned before, I have used it for logging purposes. Here is a sample code that will help you getting started:
StackTrace st = new StackTrace(3);
StackFrame sf = st.GetFrame(0);
string caller = string.Format("{0}.{1}()", sf.GetMethod().DeclaringType.FullName, sf.GetMethod().Name);
If you will print it you will get the method that called this code that is located 3rd from top in the call stack. You can modify the code:
StackTrace st = new StackTrace(3);
StackTrace st = new StackTrace(2);
StackTrace st = new StackTrace(1);
This will print the top 3 methods in the call stack.
Enjoy!
תגים:.NET, Dev