How are lambda expressions handled in C # Compiler & Virtual Machine?

How does the C#

compiler and virtual machine (.NET Common-Language-Runtime) work with functions lambda

in C#

? Are they usually translated into regular functions, but are in some sense marked as "anonymous" in the compiler and then treated as regular functions, or is there a different approach?

+3


source to share


1 answer


It is probably too wide. However, it is easy to provide some basic information:

  • First, "anonymous" simply means that there is no name by which you can refer to the method in your code. Any anonymous method declared using the older syntax delegate

    or the new lambda syntax still ends up compiling as a method with an actual name into some class (your own, or a new one generated by the compiler for this purpose ... see below). You just don't have access to the name in your own code. Apart from that, it is fundamentally like any other method.

  • The main exception to the above is how it will deal with capturing variables. If the anonymous method captures a local variable, then a new class (also hidden from your code) is declared for this purpose, and this variable is accumulated in the class instead of the actual local variable, and the anonymous method, of course, winds up in this class too.

  • Finally, note that the lambda syntax is used not only for anonymous methods, but also for declaring class instances Expression

    . In this case, some of them are similar, but of course you don't get the type compiled into your code as you would for an anonymous method.



As suggested by others, if you need more details, then StackOverflow is probably not the best place to answer (or if it is the best place to answer, it has already been asked and answered and you just have to look for an answer). You can use ildasm.exe, dotPeek, etc. To check the actual generated code, you can read the C # specification or you can search the Internet for other information.

+2


source







All Articles