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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With