What are C# lambda’s compiled into? A stackframe, an instance of an anonymous type, or?
I’ve read this question. Which mostly answers “why” you can’t use a lambda when also using implicit type features. But, this question is aimed at answering what construct the compiler produces to actually carry out the code of a lambda. Is it a method call of an anonymous type (something like anonymous types that implement an interface in Java?) or is it just a stack frame with references to closed variables and the accepting the parameter signature? Some lambda’s don’t close over anything — so are there then 2 different resulting outputs from the compile.
Assuming you mean “as a delegate”, then it still depends :p if it captures any variables (including “this”, which may be implicit) then those variables are actually implemented as fields on a compiler-generated type (not exposed anywhere public), and the statement body becomes a method on that capture class. If there are multiple levels of capture, the outer capture is again a field on the inner capture class. But essentially:
Is like;
Where:
This is identical to “anonymous methods”, but with different syntax.
Note that methods that do not capture state may be implemented as static methods without a capture class.
Expression trees, on the other hand… Are trickier to explain :p
But (I don’t have a compiler to hand, so bear with me):
Is something like:
(except using the non-existent “memberof” construct, since the compiler can cheat)
Expression trees are complex, but can be deconstructed and inspected – for example to translate into TSQL.