Storm
Storm

Reputation: 4445

How to find the method name of the calling method from a method at runtime?

How do I find the method name of the calling method from a method at runtime?

For example:

Class A
{
    M1()
    {
        B.M2();
    }
}

class B
{
    public static M2()
    {
        // I need some code here to find out the name of the method that
        // called this method, preferably the name of the declared type
        // of the calling method also.
    }
}

Upvotes: 0

Views: 1477

Answers (5)

Shane T
Shane T

Reputation: 212

You can do this by displaying the call stack, as illustrated in the code below. This will find the entire call stack, not just the calling method though.

void displaycallstack() {
    byte[] b;
    StackFrame sf;
    MemoryStream ms = new MemoryStream();
    String s = Process.GetCurrentProcess().ProcessName;
    Console.Out.WriteLine(s + " Call Stack");
    StackTrace st = new StackTrace();
    for (int a = 0;a < st.FrameCount; a++) {
        sf = st.GetFrame(a);
        s = sf.ToString();
        b = Encoding.ASCII.GetBytes(s);
        ms.Write(b,0,b.Length); 
    }
    ms.WriteTo(System.Console.OpenStandardOutput());
}

Upvotes: 0

ALOR
ALOR

Reputation: 545

Better not to use StackFrame, because there are some .NET security issues. If the code is not fully trusted, the expression "new StackFrame()" will throw a security exception.

To get the current method use:

MethodBase.GetCurrentMethod().Name

About getting calling the method, see Stack Overflow question Object creation, how to resolve "class-owner"?.

Upvotes: 0

SimSimY
SimSimY

Reputation: 3686

Check the System.Diagnostics.Trace class, but as far as I know - there is performance price when using it

Upvotes: 0

James
James

Reputation: 82096

I think you are looking for:

using System.Diagnostics;

StackTrace stackTrace = new StackTrace();
stackTrace.GetFrame(1).GetMethod().Name;

Upvotes: 1

Thomas Zoechling
Thomas Zoechling

Reputation: 34253

You can try:

using System.Diagnostics;

StackTrace stackTrace = new StackTrace();
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

Upvotes: 10

Related Questions