Lambda Expressions in VB9

Sun, February 18, 2007, 06:54 PM under dotNET | Orcas | LINQ
This short blog entry assumes that you have read my description of C# lambda expressions and here I will literally just show you the proposed VB syntax that corresponds to the lambda we ended up with in that blog post: i => i > 2. The corresponding syntax is: Function(x) i > 2

So, the full example, given the following code:
  Delegate Function SomeDelegate(ByVal i As Integer) As Boolean
Public Sub SomeMethod()
'
'REMEMBER FROM LAST TIME, THE KEY LINE IS THE FOLLOWING
Dim sd As SomeDelegate = New SomeDelegate(AddressOf OtherMethod)
'
' other code here
YetOneMore(sd)
End Sub
Private Function OtherMethod(ByVal i As Integer) As Boolean
Return i > 2
End Function
Private Sub YetOneMore(ByVal f As SomeDelegate)
Dim res As Boolean = f(5)
Console.WriteLine(res.ToString())
End Sub
We can get rid of the OtherMethod method completely and inline on the delegate creation line using the VB9 lambda expression sysntax, like this:
    Dim sd As SomeDelegate = Function(i) i > 2

WARNING: for this feature only and for the VB case only, I do not have a compiler that supports it yet. Unlike all my other blog posts, I am basing the above on a spec rather than hands on experience. If I find that it changes when I get new bits, I will come back here and update this.
Comments are closed.