How to Find the Method That Called the Current Method

How can I find the method that called the current method?

Try this:

using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace();
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

one-liner:

(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name

It is from Get Calling Method using Reflection [C#].

How do I get the calling method name and type using reflection?

public class SomeClass
{
public void SomeMethod()
{
StackFrame frame = new StackFrame(1);
var method = frame.GetMethod();
var type = method.DeclaringType;
var name = method.Name;
}
}

Now let's say you have another class like this:

public class Caller
{
public void Call()
{
SomeClass s = new SomeClass();
s.SomeMethod();
}
}

name will be "Call" and type will be "Caller".

UPDATE: Two years later since I'm still getting upvotes on this

In .NET 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute.

Going with the previous example:

public class SomeClass
{
public void SomeMethod([CallerMemberName]string memberName = "")
{
Console.WriteLine(memberName); // Output will be the name of the calling method
}
}

How to get the name of the current method from code

using System.Diagnostics;
...

var st = new StackTrace();
var sf = st.GetFrame(0);

var currentMethodName = sf.GetMethod();

Or, if you'd like to have a helper method:

[MethodImpl(MethodImplOptions.NoInlining)]
public string GetCurrentMethod()
{
var st = new StackTrace();
var sf = st.GetFrame(1);

return sf.GetMethod().Name;
}

Updated with credits to @stusmith.

Getting the name of the currently executing method

Thread.currentThread().getStackTrace() will usually contain the method you’re calling it from but there are pitfalls (see Javadoc):

Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

How to invoke a method that called the current method in c#

I see some ambiguity in your question use case..

Let us take a simple use case: You want to call some one and they in turn call you back. Is there any use to it and when do you want to stop this and go ahead to get some work done?!

For example following code like what you are expecting will go in infinite recursion and result in StackOverflowException

class MyClass
{
public void TargetMethod(Action callback)
{
Console.WriteLine("Inside TargetMethod");

callback(); //This call the SourceMethod() and which inturn call TargetMethod() again in infinite recursion.
}

public void SourceMethod()
{
Console.WriteLine("Inside SourceMethod");
TargetMethod(SourceMethod);
}
}

//Calling code
MyClass objMyClass = new MyClass();
objMyClass.SourceMethod();

Instead you can use Callback mechanism, so that once you done within the target method, notify another handler method that in turn can do some stuff like logging or updating UI etc., case specific stuff.

class MyClass
{
public void TargetMethod(Action callback)
{
Console.WriteLine("Inside TargetMethod");

callback(); //This calls/notify the handler to do some stuff.
}

public void SourceMethod()
{
Console.WriteLine("Inside SourceMethod");
TargetMethod(CallbackHandler); //Notice here we are calling to a handler which can do some stuff for us.
}

public void CallbackHandler()
{
Console.WriteLine("Inside CallbackHandler");
}
}

This code is just for quick demonstration purpose and you can enhance design further in your implementation.

Hope this provide you some heads-up on why you need to revisit your design..

How do I find the caller of a method using stacktrace or reflection?

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()

According to the Javadocs:

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

You will have to experiment to determine which index you want
(probably stackTraceElements[1] or [2]).

How to get the name of current function?

Try this:

System.Reflection.MethodBase.GetCurrentMethod().Name 

How to get Class name that is calling my method?

You can use StackFrame of System.Diagnostics and MethodBase of System.Reflection.

StackFrame(Int32, Boolean) initializes a new instance of the StackFrame class that corresponds to a frame above the current stack frame, optionally capturing source information.

MethodBase, provides information about methods and constructors.

public static string NameOfCallingClass()
{
string fullName;
Type declaringType;
int skipFrames = 2;
do
{
MethodBase method = new StackFrame(skipFrames, false).GetMethod();
declaringType = method.DeclaringType;
if (declaringType == null)
{
return method.Name;
}
skipFrames++;
fullName = declaringType.FullName;
}
while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));

return fullName;
}

Your logger classes call this method:

public static void Error()
{
string name = NameOfCallingClass();
}


Related Topics



Leave a reply



Submit