Someone today asked me a question which I found intresting and is fairly usefull in debugging. The questions was “How do I figure out which function called my function”. In other words they wanted to note their caller without throwing an exception etc. This is quite easily done by using the StackFrame object in System.Diagnostics just promise you won’t use this in lieu of encapsulation J i.e. NEVER use this as a conditional in your code
if(IamCalledBySomeFunction) {
//do one behavior
} else {
//do another behavior
}
Here is a full example:
using System;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Method1() {
StackFrame Frame = new StackFrame(1,true); //only go up 1 level
Console.WriteLine("Called by method " + Frame.GetMethod().ToString() + " at " + Frame.GetFileName() + ":" + Frame.GetFileLineNumber());
}
static void Method2() {
Method1();
}
static void Main(string[] args) {
Method1();
Method2();
}
}
}
As a thought this could be quite intresting to use when dealing with aspects as well (conditional placement of aspects dependant upon call stack)