SpicyCode

The ramblings of Chad Humphries

Reflection – Discover your calling method and retrieve it’s information

I love reflection. It’s my favorite part of the framework. I’ve been digging around trying to find a way to get the calling methods information. I’ve read a several newsgroup postings and the msdn reference. The result is below.

.csharpcode { font-size: 10pt; color: black; font-family: Courier New , Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0px; } .rem { color: #008000; } .kwrd { color: #0000ff; } .str { color: #006080; } .op { color: #0000c0; } .preproc { color: #cc6633; } .asp { background-color: #ffff00; } .html { color: #800000; } .attr { color: #ff0000; } .alt { background-color: #f4f4f4; width: 100%; margin: 0px; } .lnum { color: #606060; }

using System.Diagnostics;
using System.Reflection;

namespace SpicyCode.Reflection
{
public class DiscoverCaller
{
  private DiscoverCaller()  {  }
  public static void PrintCallerInfo()
  {
    System.Web.HttpContext context = System.Web.HttpContext.Current;
    StackFrame currentFrame = new StackFrame(1, true);

    // Now get the MethodBase associated with that frame.
    MethodBase currentMethod = currentFrame.GetMethod();
    // Some useful properties listed below.
    // currentFrame.GetFileLineNumber()
    // currentFrame.GetFileColumnNumber()
    // currentFrame.GetFileName()
    // currentMethod.Name
    // currentMethod.ReflectedType
  }
}
}

You can call the method like this

 SpicyCode.Reflection.DiscoverCaller.PrintCallerInfo() ;

You’ll get a print out of all relevant info.

Advertisements

Written by spicycode

December 3, 2004 at 6:15 pm

Posted in programming

Tagged with

%d bloggers like this: