Why does reflection return such a strange name for lambda?

I have this code:

class Program { static void Main(string[] args) { Action whatToDo = () => { var member = (MemberInfo)(MethodBase.GetCurrentMethod()); Thread.Sleep(0); //whatever, need something to put a breakpoint on }; whatToDo(); } } 

when I run it and use the clock to view the object attached to the member link, I see that the MemberInfo.Name property has the value <Main>b__0 .

It looks weird. Why didn't reflection use the name whatToDo ? What if I had more than one action with the same signature inside the same member function - how would I say which one is listed?

Why is such a strange name returned by reflection?

+1
source share
1 answer

Lambda expressions that are converted to delegates are converted to methods. Your code is equivalent to:

 class Program { static void Main(string[] args) { Action whatToDo = MyLambda; // Method group conversion whatToDo(); } static void MyLambda() { var member = (MemberInfo)(MethodBase.GetCurrentMethod()); Thread.Sleep(0); //whatever, need something to put a breakpoint on } } 

... except that the compiler is smart enough to create new classes where necessary for captured variables, etc. Although my conversion has an additional method called MyLambda , the C # compiler generates unspeakable names that are not valid C # identifiers (to avoid collisions, do not let you access them directly, etc.).

+9
source

All Articles