Geeks With Blogs
Greg Young Greg.ToString()

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)

 

 

Posted on Friday, December 2, 2005 6:38 PM | Back to top


Comments on this post: hmm this could have some intresting uses

# re: hmm this could have some intresting uses
Requesting Gravatar...
Another similar method is Environment.StackTrace. It's a string that looks just like an Exception's full stack trace. I agree not to use it as a condition - too unpredictable.

I was considering using it as a condition, but the calling methods may have been my own method or Reflection methods, so I figured it would be too unreliable.

I haven't run Greg's StackFrame, so I'm not sure the difference between the two. In addition, System.Diagnostics has a StackTrace class. I'll have to play around with the three to see which is the most useful.
Left by Joe Balfantz on Jan 31, 2006 9:54 AM

Your comment:
 (will show your gravatar)


Copyright © Greg Young | Powered by: GeeksWithBlogs.net