Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are lambdas resolved in the .NET framework?

For example, you can use lambda expressions in Visual Studio 2010, but still target .NET 2.0.

How does the compiler resolve lambda expressions to work with an older framework that does not include this feature?

like image 411
Joseph Nields Avatar asked May 06 '15 14:05

Joseph Nields


1 Answers

Lambdas have no reliance on any of the newer framework features. A lambda, at the end of the day, only needs to be able to create a new class with fields, methods, and constructors, all of which is available in the 1.0 runtime/framework.

The following code:

int value = 42;
MyDelegate f = () => value;

Will be transformed into a new named type:

public class SomeRandomCompilerGeneratedNameGoesHere
{
    public int value;
    public int SomeGeneratedMethodName()
    {
        //the content of the anonymous method goes here
        return value;
    }
}

And will be used like so:

var closureClass = new SomeRandomCompilerGeneratedNameGoesHere();
closureClass.value = 42;
MyDelegate f = closureClass.SomeGeneratedMethodName;

Now, there are a few situations that don't require all of this; if there are no closed over values some of these steps can be elated, and optimizations added (i.e. the method can be made static, to avoid the creation of an object instance), but the transformation shown here is capable of mapping any valid C# lambda, and as you can see, the code it's transformed into would be valid even in C# 1.0.

like image 86
Servy Avatar answered Sep 22 '22 02:09

Servy