Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a name of calling method?

Tags:

.net

can Log method of class A get to know who calls it ?

class A
{
    public void Log(string msg)
    {
        Log.Write("method_name: " + msg);
    }
}

I want to know a name of class and a name of a method.

like image 236
nik Avatar asked Aug 16 '10 06:08

nik


1 Answers

You can use the StackTrace and StackFrame classes. You can either get a whole stack trace by calling the StrackTrace constructor, or just a particular stack frame using the StackFrame constructor which takes the number of frames to skip.

You should be aware that it can be inaccurate due to inlining. (e..g method A inlines method B which calls your method - method A will be reported, not B).

Sample code:

using System;
using System.Diagnostics;

class Test
{
    static void ShowCaller()
    {
        // Use this code if you want multiple frames
        // StackTrace trace = new StackTrace();
        // StackFrame frame = trace.GetFrame(1);

        // Use this code if you're only interested in one frame
        StackFrame frame = new StackFrame(1);
        Console.WriteLine(frame.GetMethod());
    }

    static void Intermediate()
    {
        ShowCaller();
    }

    static void Main()
    {
        Intermediate();
    }
}

Running as an optimized release build, this will print Void Main() - when running a debug build, or if you put more code into the Intermediate() method, it will print Void Intermediate().

(As mentioned in comments, this will also create a performance hit. You should measure it to see if it's acceptable in your particular case.)

like image 64
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet