652

When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like Assembly.GetCallingAssembly() but for methods.

4
  • 24
    If you are using .net 4.5 beta +, you can use CallerInformation API. Mar 11, 2012 at 7:17
  • 7
    Caller Information is also much faster
    – dove
    Nov 21, 2012 at 15:08
  • 10
    I created a quick BenchmarkDotNet benchmark of the three main methods (StackTrace, StackFrame and CallerMemberName) and posted the results as a gist for others to see here: gist.github.com/wilson0x4d/7b30c3913e74adf4ad99b09163a57a1f
    – wilson0x4d
    Mar 17, 2018 at 20:02
  • Just in case you want to find where your method is called without running it, keep in mind Shift+F12 doesn't work if the method is called via Reflection. Sometimes you have to use Ctrl+F to search for the method name string. Jan 19, 2021 at 9:56

18 Answers 18

661

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
13
  • 15
    You can also create just the frame you need, rather than the entire stack: Oct 6, 2008 at 13:05
  • 245
    new StackFrame(1).GetMethod().Name; Oct 6, 2008 at 13:05
  • 14
    This isn't entirely reliable though. Let's see if this works in a comment! Try the following in a console application and you see that compiler optimsations break it. static void Main(string[] args) { CallIt(); } private static void CallIt() { Final(); } static void Final() { StackTrace trace = new StackTrace(); StackFrame frame = trace.GetFrame(1); Console.WriteLine("{0}.{1}()", frame.GetMethod().DeclaringType.FullName, frame.GetMethod().Name); }
    – BlackWasp
    Jun 1, 2009 at 15:13
  • 12
    This doesn't work when the compiler inlines or tail-call optimizes the method, in which case the stack is collapsed and you will find other values than expected. When you only use this in Debug builds, it'll work well though.
    – Abel
    Mar 19, 2012 at 12:27
  • 53
    What I have done in the past is add the compiler attribute [MethodImplAttribute(MethodImplOptions.NoInlining)] before the method that will look up the stack trace. That ensures that the compiler will not in-line the method, and the stack trace will contain the true calling method (I'm not worried about tail-recursion in most cases.) Aug 3, 2012 at 19:52
521

In C# 5, you can get that information using caller info:

//using System.Runtime.CompilerServices;
public void SendError(string Message, [CallerMemberName] string callerName = "") 
{ 
    Console.WriteLine(callerName + "called me."); 
} 

You can also get the [CallerFilePath] and [CallerLineNumber].

10
  • 15
    Hello, it's not C# 5, it is available in 4.5.
    – AFract
    Feb 16, 2015 at 14:06
  • 64
    @AFract Language (C#) versions are not the same as .NET version. Feb 22, 2015 at 21:22
  • 7
    @stuartd Looks like [CallerTypeName] was dropped from current .Net framework (4.6.2) and Core CLR
    – Ph0en1x
    Apr 13, 2016 at 12:30
  • 4
    @Ph0en1x it was never in the framework, my point was it would be handy if it was, eg how to get Type name of a CallerMember
    – stuartd
    Apr 13, 2016 at 14:24
  • 4
    @DiegoDeberdt - I've read that using this has no reflection downsides since it does all the work at compile time. I believe it's accurate as to what called the method. May 28, 2017 at 8:46
132

You can use Caller Information and optional parameters:

public static string WhoseThere([CallerMemberName] string memberName = "")
{
    return memberName;
}

This test illustrates this:

[Test]
public void Should_get_name_of_calling_method()
{
    var methodName = CachingHelpers.WhoseThere();
    Assert.That(methodName, Is.EqualTo(nameof(Should_get_name_of_calling_method)));
}

While the StackTrace works quite fast above and would not be a performance issue in most cases the Caller Information is much faster still. In a sample of 1000 iterations, I clocked it as 40 times faster.

8
  • 2
    Only available from .Net 4.5 though
    – DerApe
    Jul 6, 2015 at 10:41
  • 1
    Note that this does not work, if the caller passes an agrument: CachingHelpers.WhoseThere("wrong name!"); ==> "wrong name!" because the CallerMemberName is only substitutes the default value. Dec 6, 2017 at 16:09
  • @OlivierJacot-Descombes is does not work in that way in the same way an extension method would not work if you passed a parameter to it. you could though another string parameter which could be used. Also note that resharper would give you a warning if you tried to passed an argument like you did.
    – dove
    Dec 6, 2017 at 16:30
  • 1
    @dove you can pass any explicit this parameter into an extension method. Also, Olivier is correct, you can pass a value and [CallerMemberName] is not applied; instead it functions as an override where the default value would normally be used. As a matter of fact, if we look at the IL we can see that the resulting method is no different than what would normally have been emitted for an [opt] arg, the injection of CallerMemberName is therefore a CLR behavior. Lastly, the docs: "The Caller Info attributes [...] affect the default value that's passed in when the argument is omitted"
    – wilson0x4d
    Mar 17, 2018 at 18:35
  • 4
    This is perfect and is async friendly which StackFrame won't help you with. Also doesn't affect being called from a lambda.
    – Aaron
    Mar 6, 2019 at 1:25
102

A quick recap of the 2 approaches with speed comparison being the important part.

http://geekswithblogs.net/BlackRabbitCoder/archive/2013/07/25/c.net-little-wonders-getting-caller-information.aspx

Determining the caller at compile-time

static void Log(object message, 
[CallerMemberName] string memberName = "",
[CallerFilePath] string fileName = "",
[CallerLineNumber] int lineNumber = 0)
{
    // we'll just use a simple Console write for now    
    Console.WriteLine("{0}({1}):{2} - {3}", fileName, lineNumber, memberName, message);
}

Determining the caller using the stack

static void Log(object message)
{
    // frame 1, true for source info
    StackFrame frame = new StackFrame(1, true);
    var method = frame.GetMethod();
    var fileName = frame.GetFileName();
    var lineNumber = frame.GetFileLineNumber();

    // we'll just use a simple Console write for now    
    Console.WriteLine("{0}({1}):{2} - {3}", fileName, lineNumber, method.Name, message);
}

Comparison of the 2 approaches

Time for 1,000,000 iterations with Attributes: 196 ms
Time for 1,000,000 iterations with StackTrace: 5096 ms

So you see, using the attributes is much, much faster! Nearly 25x faster in fact.

1
  • 1
    This method seem to be superior approach. It also works in Xamarin without a problem of namespaces not being available. Sep 19, 2017 at 14:18
70

We can improve on Mr Assad's code (the current accepted answer) just a little bit by instantiating only the frame we actually need rather than the entire stack:

new StackFrame(1).GetMethod().Name;

This might perform a little better, though in all likelihood it still has to use the full stack to create that single frame. Also, it still has the same caveats that Alex Lyman pointed out (optimizer/native code might corrupt the results). Finally, you might want to check to be sure that new StackFrame(1) or .GetFrame(1) don't return null, as unlikely as that possibility might seem.

See this related question: Can you use reflection to find the name of the currently executing method?

2
  • 1
    is it even possible that new ClassName(…) equals to null? Mar 6, 2015 at 10:26
  • 1
    What's nice is that this also works in .NET Standard 2.0.
    – srbrills
    Nov 7, 2017 at 18:15
61

In general, you can use the System.Diagnostics.StackTrace class to get a System.Diagnostics.StackFrame, and then use the GetMethod() method to get a System.Reflection.MethodBase object. However, there are some caveats to this approach:

  1. It represents the runtime stack -- optimizations could inline a method, and you will not see that method in the stack trace.
  2. It will not show any native frames, so if there's even a chance your method is being called by a native method, this will not work, and there is in-fact no currently available way to do it.

(NOTE: I am just expanding on the answer provided by Firas Assad.)

2
  • 2
    In debug mode with optimizations turned off, would you be able to see what the method is in the stack trace? Jan 21, 2011 at 3:36
  • 1
    @AttackingHobo: Yes--unless the method is inlined (optimizations on) or a native frame, you'll see it.
    – Alex Lyman
    Jan 25, 2011 at 19:19
53

As of .NET 4.5 you can use Caller Information Attributes:

  • CallerFilePath - The source file that called the function;
  • CallerLineNumber - Line of code that called the function;
  • CallerMemberName - Member that called the function.

    public void WriteLine(
        [CallerFilePath] string callerFilePath = "", 
        [CallerLineNumber] long callerLineNumber = 0,
        [CallerMemberName] string callerMember= "")
    {
        Debug.WriteLine(
            "Caller File Path: {0}, Caller Line Number: {1}, Caller Member: {2}", 
            callerFilePath,
            callerLineNumber,
            callerMember);
    }
    

 

This facility is also present in ".NET Core" and ".NET Standard".

References

  1. Microsoft - Caller Information (C#)
  2. Microsoft - CallerFilePathAttribute Class
  3. Microsoft - CallerLineNumberAttribute Class
  4. Microsoft - CallerMemberNameAttribute Class
19

Obviously this is a late answer, but I have a better option if you can use .NET 4.5 or newer:

internal static void WriteInformation<T>(string text, [CallerMemberName]string method = "")
{
    Console.WriteLine(DateTime.Now.ToString() + " => " + typeof(T).FullName + "." + method + ": " + text);
}

This will print the current Date and Time, followed by "Namespace.ClassName.MethodName" and ending with ": text".
Sample output:

6/17/2016 12:41:49 PM => WpfApplication.MainWindow..ctor: MainWindow initialized

Sample use:

Logger.WriteInformation<MainWindow>("MainWindow initialized");
1
  • Great answer. It sucks that the CallerMemberName has to be defined as a parameter, though. It's often common to pass in a params array as the final parameter of a log method, which makes it difficult to combine these two things.
    – devklick
    Jun 18, 2023 at 11:00
14

Note that doing so will be unreliable in release code, due to optimization. Additionally, running the application in sandbox mode (network share) won't allow you to grab the stack frame at all.

Consider aspect-oriented programming (AOP), like PostSharp, which instead of being called from your code, modifies your code, and thus knows where it is at all times.

1
  • You're absolutely correct that this won't work in release. I'm not sure I like the idea of code injection, but I guess in a sense a debug statement requires code modification, but still. Why not just go back to C macros? It's at least something you can see.
    – ebyrob
    Jun 20, 2017 at 14:56
9
/// <summary>
/// Returns the call that occurred just before the "GetCallingMethod".
/// </summary>
public static string GetCallingMethod()
{
   return GetCallingMethod("GetCallingMethod");
}

/// <summary>
/// Returns the call that occurred just before the the method specified.
/// </summary>
/// <param name="MethodAfter">The named method to see what happened just before it was called. (case sensitive)</param>
/// <returns>The method name.</returns>
public static string GetCallingMethod(string MethodAfter)
{
   string str = "";
   try
   {
      StackTrace st = new StackTrace();
      StackFrame[] frames = st.GetFrames();
      for (int i = 0; i < st.FrameCount - 1; i++)
      {
         if (frames[i].GetMethod().Name.Equals(MethodAfter))
         {
            if (!frames[i + 1].GetMethod().Name.Equals(MethodAfter)) // ignores overloaded methods.
            {
               str = frames[i + 1].GetMethod().ReflectedType.FullName + "." + frames[i + 1].GetMethod().Name;
               break;
            }
         }
      }
   }
   catch (Exception) { ; }
   return str;
}
1
  • oops, I should have explained the "MethodAfter" param a little better. So if you are calling this method in a "log" type function, you'll want to get the method just after the "log" function. so you would call GetCallingMethod("log"). -Cheers
    – Flanders
    May 28, 2010 at 20:10
7

Maybe you are looking for something like this:

StackFrame frame = new StackFrame(1);
frame.GetMethod().Name; //Gets the current method name

MethodBase method = frame.GetMethod();
method.DeclaringType.Name //Gets the current class name
4
private static MethodBase GetCallingMethod()
{
  return new StackFrame(2, false).GetMethod();
}

private static Type GetCallingType()
{
  return new StackFrame(2, false).GetMethod().DeclaringType;
}

A fantastic class is here: http://www.csharp411.com/c-get-calling-method/

1
  • StackFrame is not reliable. Going up "2 frames" might easily go back too method calls. Nov 7, 2016 at 3:37
4

For getting Method Name and Class Name try this:

    public static void Call()
    {
        StackTrace stackTrace = new StackTrace();

        var methodName = stackTrace.GetFrame(1).GetMethod();
        var className = methodName.DeclaringType.Name.ToString();

        Console.WriteLine(methodName.Name + "*****" + className );
    }
3

Another approach I have used is to add a parameter to the method in question. For example, instead of void Foo(), use void Foo(string context). Then pass in some unique string that indicates the calling context.

If you only need the caller/context for development, you can remove the param before shipping.

3

Extra information to Firas Assaad answer.

I have used new StackFrame(1).GetMethod().Name; in .net core 2.1 with dependency injection and I am getting calling method as 'Start'.

I tried with [System.Runtime.CompilerServices.CallerMemberName] string callerName = "" and it gives me correct calling method

1

We can also use lambda's in order to find the caller.

Suppose you have a method defined by you:

public void MethodA()
    {
        /*
         * Method code here
         */
    }

and you want to find it's caller.

1. Change the method signature so we have a parameter of type Action (Func will also work):

public void MethodA(Action helperAction)
        {
            /*
             * Method code here
             */
        }

2. Lambda names are not generated randomly. The rule seems to be: > <CallerMethodName>__X where CallerMethodName is replaced by the previous function and X is an index.

private MethodInfo GetCallingMethodInfo(string funcName)
    {
        return GetType().GetMethod(
              funcName.Substring(1,
                                funcName.IndexOf("&gt;", 1, StringComparison.Ordinal) - 1)
              );
    }

3. When we call MethodA the Action/Func parameter has to be generated by the caller method. Example:

MethodA(() => {});

4. Inside MethodA we can now call the helper function defined above and find the MethodInfo of the caller method.

Example:

MethodInfo callingMethodInfo = GetCallingMethodInfo(serverCall.Method.Name);
0
StackFrame caller = (new System.Diagnostics.StackTrace()).GetFrame(1);
string methodName = caller.GetMethod().Name;

will be enough, I think.

0
public static string GetCallerFullName<T>(this T callingObject,[CallerMemberName] string caller = default) =>$"{callingObject.GetType().Name}:{caller}";

This is a slight improvement to Camilo Terevinto's solution because the calling convention is bit cleaner

this.GetCallerFullName();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.