DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Updated on

Who am I? Me, the name of the currently executing method in C#

I have a function in my JavaScript collection which gives me the name of the currently executing function.

function CalleeName(a) {
  return a.callee.toString().split(" ")[1].split("(")[0].trim();
}
Enter fullscreen mode Exit fullscreen mode

To make it work I have to provide the arguments object as the parameter, viz

function foo() {
  var me = CalleeName(arguments);
  // ..
}
Enter fullscreen mode Exit fullscreen mode

Today I found out how to do the same thing in C#. I find this helpful for logs and status messages.

// method version
private static string Me() => new StackTrace().GetFrame(1).GetMethod().Name;

// or property version
private static string Me => new StackTrace().GetFrame(1).GetMethod().Name;
Enter fullscreen mode Exit fullscreen mode

That gives the name of the parent of the currently executing method. You may wonder how that helps, but in the context of a C# program, evaluating Me returns the name of the method that called Me which in this case turns out to be the current method.

So running this

using System;
using System.Diagnostics;

namespace dotnets
{
    class Program
    {
        private static string Me => new StackTrace().GetFrame(1).GetMethod().Name;

        static void Main(string[] args)
        {
            Console.WriteLine(Me);
            foo();
        }

        static void foo()
        {
            Console.WriteLine(Me);
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

displays Main then foo.

Top comments (6)

Collapse
 
thebuzzsaw profile image
Kelly Brown

Get the name at compile-time instead!

public static string? Me([CallerMemberName] string? cmn = null) => cmn;
Collapse
 
bugmagnet profile image
Bruce Axtens

Needs using System.Runtime.CompilerServices; or public static string? Me([System.Runtime.CompilerServices.CallerMemberName] string? cmn = null) => cmn;

Collapse
 
bugmagnet profile image
Bruce Axtens

Can't wait to try it. A pity I can only click the <3 button once.

Collapse
 
integerman profile image
Matt Eland

Note that getting the current executing method via a stack trace is an expensive operation.

You can also use the nameof keyword to encode the name of a method, parameter, or member at compile time.

Collapse
 
sebbdk profile image
Sebastian Vargr • Edited

Where would this be use full, error reporting maybe?

This reminds me of inflection, which have caused me a lot of debugging grief in my career, so i would be cautious about applications of it. :/

Collapse
 
bugmagnet profile image
Bruce Axtens

Yes, does use reflection so could be problematic in a Release build.