nik
nik

Reputation: 895

How to get a name of calling method?

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.

Upvotes: 5

Views: 772

Answers (5)

RDultsin
RDultsin

Reputation: 1

Starting .NET 4.5 you can get caller information through CallerMemberNameAttribute, which is a part of System.Runtime.CompilerServices namespace:

using System.Runtime.CompilerServices;

class A
{
    public void Log(string msg, [CallerMemberName] string memberName = "")
    {
        Log.Write("{0}: {1}", memberName, msg);
    }
}

Upvotes: 0

anishMarokey
anishMarokey

Reputation: 11387

you can also try:

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


        using System.Reflection;

class TestClass
{
       // in method

        private void TestMethod()
    {
           A.Log(MethodBase.GetCurrentMethod().Name +MethodBase.GetCurrentMethod().DeclaringType.FullName);
    }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503934

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.)

Upvotes: 4

Will A
Will A

Reputation: 25018

Yes, it can - by creating a new StackTrace object and then use stackTrace.GetFrame(1).GetMethod().Name - however, this is likely an expensive operation, so test and check that it doesn't cause undue slowdown of your application.

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129832

You can always step back in the call stack

Upvotes: 2

Related Questions