Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

lambda

clr

How does C# Compiler and Virtual Machine (.NET Common-Language-Runtime) handle lambda functions in C#? Are they generally translated into normal functions but marked as "anonymous" in a sense in the compiler and then treated as normal functions or is there a different approach?

like image 714
Nick Louloudakis Avatar asked Dec 05 '25 08:12

Nick Louloudakis


1 Answers

It probably is too broad. That said, some basic information can be easily provided:

  • First, "anonymous" simply means that there is no name by which you can refer to the method in your code. Any anonymous method, whether declared using the older delegate syntax or the newer lambda syntax, still winds up being compiled as a method, with an actual name, into some class (either your own or a new one the compiler creates for the purpose…see below). You simply don't have access to the name in your own code. Other than that, it is fundamentally just like any other method.

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

  • Finally note that the lambda syntax is use not just for anonymous methods, but also to declare instances of the Expression class. In that scenario, some of the handing is similar, but of course you don't get a type compiled into your code the way you would for an anonymous method.

As others have suggested, if you need more detail than that, then StackOverflow probably is not the best place for the answer (or, if it is the best place for the answer, surely it's already been asked and answered and you just need to search for the answer). You can use ildasm.exe, dotPeek, etc. to inspect the actual generated code, you can read the C# specification, or you can search the web for other details.

like image 122
Peter Duniho Avatar answered Dec 07 '25 21:12

Peter Duniho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!