1

In Java we can get the method name using the Method in java.lang.reflect API. For example

public void GetmethodName(Method method)
{
  String testName = method.getName();

}

Can I achieve this using the refection API or Diagnostics API in c#

Johnny_347
  • 33
  • 1
  • 6
  • 1
    What is the expected value of `testName` here? I don't want to make any assumptions, although I *think* I know what you're after. – Broots Waymb Mar 12 '20 at 14:31
  • 1
    Dont use reflection in C# 6 and up, use `nameof(MethodName)` instead. – Fixation Mar 12 '20 at 14:33
  • @Fixation oh, there are plenty of times when `MethodInfo`-based reflection is entirely appropriate; really it depends on context (which we don't have here) – Marc Gravell Mar 12 '20 at 14:33
  • I understand that, but I dont see why we recommend reflection before mentioning `nameof()`. – Fixation Mar 12 '20 at 14:36

3 Answers3

3

Very similarly:

public void GetMethodName(MethodInfo method)
{
  string testName = method.Name;
}

where you can get the MethodInfo via a Type instance, i.e. typeof(Foo).GetMethod(...) or someTypeInstance.GetMethods(...)

Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
2

You could use CallerMemberNameAttribute

public void GetmethodName([CallerMemberName] string methodname = null)
{
  Console.WriteLine(methodname);
}

When using CallerMemberNameAttribute, the compiler directly hard code (check the ldstr instruction) the method name during compilation and would not require reflection. For example,

void Foo()
{
    GetmethodName();
}

Looking at the IL Code

IL_0000:  nop         
IL_0001:  ldarg.0     
IL_0002:  ldstr       "Foo"
IL_0007:  call        UserQuery.GetmethodName
IL_000C:  nop         
IL_000D:  ret    
Anu Viswan
  • 16,800
  • 2
  • 18
  • 44
0

It is possible to get the methods name using reflection:

using System.Reflection;

// ...

public class MyClass
{    
    public void MyMethod()
    {
        MethodBase m = MethodBase.GetCurrentMethod();

        // This will write "MyClass.MyMethod" to the console
        Console.WriteLine($"Executing {m.ReflectedType.Name}.{m.Name}");
    }
}
TobiHatti
  • 56
  • 4
  • 1
    If you're after the *current* method's name, you wouldn't do that though; you'd just write a `static string CurrentMethodName([CallerMemberName] string caller = null) => caller;` and just do `string whoAmI = CurrentMethodName();` - or just `string whoAmI = nameof(TheMethodYouAreIn);` (if you just want to avoid a string literal) – Marc Gravell Mar 12 '20 at 14:34