How to get Method name in c# as a string?

10.2k views Asked by At

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#

3

There are 3 answers

0
Marc Gravell On

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(...)

1
TobiHatti On

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}");
    }
}
2
Anu Viswan On

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