How is lambdas allowed in .NET?

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

How does the compiler allow lambda expressions to work with an old structure that does not include this function?

+7
c # lambda
source share
2 answers

Lambdas does not rely on any of the new features of the framework. A lambda, after all, should only be able to create a new class with fields, methods, and constructors, all of which are available in the 1.0 runtime.

The following code:

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

Will be converted to a new named type:

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

And it will be used like this:

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

Now there are several situations that do not require all this; if there are no private values, some of these steps can be raised and optimizations added (i.e. the method can be made static to avoid creating an instance of the object), but the conversion given here can display any valid C # lambda, and, as you can see the code that he converted will be valid even in C # 1.0.

+8
source share

Lambda expressions are compiler functions. You do not need support for a framework or CLR.

The compiler will create a method for you and perform the implicit conversion of delegates, and all of these materials are for you. All you need is a new compiler that implements the function.

Most language features are not associated with any version of the .Net framework. Some of them just work; some of them can be customized with some tricks.

For example: Implicit delegate conversion, Collection initializer, Object initializer will work as it is. Extension methods can be used with some tricks.

See John's article , "Using C # 3 in .NET 2.0 and 3.0," for details.

FWIW, using only the same BCL.Async concept , includes asynchronous wait functionality in .Net 4.0, which was released with .net 4.5.

+5
source share

All Articles