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?
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.
Lambda expressions are compiler features. You don't need a framework or CLR support for it.
Compiler will create a method for you and perform the implicit delegate conversion and all those stuff for you. All you need is the new compiler in which the feature was implemented.
Most of the language features aren't tied with any version of .Net framework. Some of them just work; some of them can be tweaked using some tricks.
For example: Implicit delegate conversion, Collection Initializer, Object Initializer will work as it is. Extension methods can be used with some tricks.
Refer Jon's article, "Using C# 3 in .NET 2.0 and 3.0" section for more information.
FWIW, Using the same concept only BCL.Async library enables async-await feature in .Net 4.0 which was released along with .net 4.5.