Does VB.NET and Visual Studio 2010 support a multi-line anonymous method?

I found that this answer was asked and answered before VS2010 was actually released.

They say that

VB9 has only one line anonymous functions. We add full operator and multi-line lambdas to VB10.

But I tried to add this code

Dim test2 = Function(t1 As T, t2 As T) ( Dim val1 As IComparable = DirectCast(prop.GetValue(t1), IComparable) Dim val2 As IComparable = DirectCast(prop.GetValue(t2), IComparable) Return val1.CompareTo(val2) ) 

for the .NET Framework 4.0 project in Visual Studio 2010 and it does not compile.

You now, if this function is really implemented and what am I doing wrong?

+4
source share
3 answers

I believe that you are missing your line of "Final Function". Try the following:

  Dim test2 = (Function(t1 As T, t2 As T) Dim val1 As IComparable = DirectCast(prop.GetValue(t1), IComparable) Dim val2 As IComparable = DirectCast(prop.GetValue(t2), IComparable) Return val1.CompareTo(val2) End Function) 
+11
source

You are missing the End Function , and you are trying to enclose the body of the function in parentheses, which is incorrect. This should work:

 Dim test2 = Function(t1 As T, t2 As T) Dim val1 As IComparable = DirectCast(prop.GetValue(t1), IComparable) Dim val2 As IComparable = DirectCast(prop.GetValue(t2), IComparable) Return val1.CompareTo(val2) End Function 

This feature is documented here:

+3
source

Here's what you might find useful. Notice how the method is declared immediately.

 Dim food = New With { .ID = 1, .Name = "Carrot", .Type = ( Function(name As String) If String.IsNullOrEmpty(name) Then Return String.Empty Select Case name.ToLower() Case "apple", "tomato": Return "Fruit" Case "potato": Return "Vegetable" End Select Return "Meat" End Function )(.Name) } Dim type = food.Type 
+2
source

All Articles