Jeff Reed
Jeff Reed

Reputation: 231

Using lambda expressions in .net 2.0 with anonymous methods

This question is related to Visual Basic .NET 2010

Okay so I use lambda expressions in my code, and I need to compile it to target the 2.0 version of the .net framework. I won't be able to use LINQ since it's 3.0 and above, but I've head that there's a possibility to use anonymous methods in the code to allow some lambda expressions.

So say that I'm using code such as:

AsyncOperation.Post(Sub(x) Something(x), Nothing)

What would the anonymous method look like to support such syntax?

Upvotes: 1

Views: 701

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

C# supports both anonymous methods and lambda expressions. Generally speaking, they both serve the same kind of purpose, but their syntax, and the way that they work, are different. VB.NET, on the other hand, only supports lambda expressions. It does not support anything equivalent to C#'s anonymous methods. However, since VB.NET's syntax for lambda expressions more closely resemble C#'s syntax for anonymous methods, it is not uncommon for people to mistakenly refer to them as "anonymous methods" in VB.NET, even though they are, in reality, lambda expressions.

Lambda expressions are not inherently supported by MSIL. They are supported by the VB.NET compiler which builds the necessary MSIL code to accomplish the desired task. Therefore, even though lambda expressions were not added until the 3.5 version of the VB.NET compiler, the 3.5 version of the framework is not required to run the MSIL code that was compiled from lambda expressions. What that means is, as long as you are compiling your VB.NET code using a 3.5 or later version of the compiler, you can target the 2.0 version of the framework even with lambda expressions.

Since Visual Studio always uses the highest version compiler, when you are using Visual Studio 2010, it will use the 3.5 version compiler, even when you are targeting earlier versions of the framework. The up-shot of all of this is that when you use Visual Studio 2010 (or later), you can use things like lambda expressions and auto-properties even when you are targeting the 2.0 framework.

Upvotes: 2

Related Questions