Using MethodInfo.GetCurrentMethod () in Anonymous Methods

public static void Main(string[] args) { Action a = () => Console.WriteLine(MethodInfo.GetCurrentMethod().Name); a(); } 

This code will return an obscure string like this: <Main>b__0 .

Is there a way to ignore anonymous methods and get a more readable method name?

+7
source share
3 answers

You can grab it outside:

 var name = MethodInfo.GetCurrentMethod().Name + ":subname"; Action a = () => Console.WriteLine(name); 

Besides; not.

+6
source

No no. That is why this is an anonymous method. The name is automatically generated by the compiler and guaranteed to be unique. If you want to get the name of the calling method, you can pass it as an argument:

 public static void Main() { Action<string> a = name => Console.WriteLine(name); a(MethodInfo.GetCurrentMethod().Name); } 

or if you really want to have a meaningful name, you need to provide it:

 public static void Main() { Action a = MeaningfullyNamedMethod; a(); } static void MeaningfullyNamedMethod() { Console.WriteLine(MethodInfo.GetCurrentMethod().Name); } 
+6
source

If you are looking for the name of the function in which the anonymous method resides, you can move the stack and get the name of the calling method. Note that this will only work until your searched method name becomes one of the steps in the hierarchy. Maybe there is a way to travel until you reach a non-anonymous method.

For more information see http://www.csharp-examples.net/reflection-calling-method-name/

+3
source

All Articles