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();
}
To make it work I have to provide the arguments
object as the parameter, viz
function foo() {
var me = CalleeName(arguments);
// ..
}
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;
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);
}
}
}
displays Main
then foo
.
Top comments (6)
Get the name at compile-time instead!
Needs
using System.Runtime.CompilerServices;
orpublic static string? Me([System.Runtime.CompilerServices.CallerMemberName] string? cmn = null) => cmn;
Can't wait to try it. A pity I can only click the <3 button once.
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.
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. :/
Yes, does use reflection so could be problematic in a Release build.