Lamba expression cannot be used as expected

2019-08-10 03:35发布

问题:

The following code produces the compiler error "Expression expected" (Sub is underlined).

Dim lambda As Action(Of Integer) = Sub(x) Console.WriteLine(x)

Why does this not work?

Note: The corresponding C# code works:

Action<int> lambda = x => Console.WriteLine(x);

回答1:

I guess you're using Visual Studio 2008. Action lambdas in VB.NET (Sub keyword) have been added in VB 10, which ships with Visual Studio 2010. The same is true for multi-line lambdas, by the way.

Note that this is not a framework issue, but a compiler issue: You can use action lambdas even in .NET 3.5 projects, as long as you use the VS 2010 compiler.

C# had action lambdas before VB, which is why the C# example works even in VS 2008.



标签: vb.net lambda