Can we please get single line lambda expressions working first?

One of the biggest pains with lambda expressions in Visual Basic is not being able to pass them as parameters to methods that expect an Action(of T).  Here’s a quick example of something you can’t do in VB.

 

Module Module1

    Sub Main()

        Dim l As New List(Of String)

        l.Add(“moe”)

        l.Add(“larry”)

        l.Add(“curly”)

        l.ForEach(Function(x) Console.WriteLine(x))

        Console.ReadLine()

    End Sub

End Module

Instead of just working, we get an “Expression does not produce a value” error.  To get the following to work we have to use our addressof operator.

 

Module Module1

    Sub Main()

        Dim l As New List(Of String)

        l.Add(“moe”)

        l.Add(“larry”)

        l.Add(“curly”)

        l.ForEach(AddressOf WriteLine)

        Console.ReadLine()

    End Sub

    Sub WriteLine(ByVal x As String)

        Console.WriteLine(x)

    End Sub

End Modul

 

There’s no problem doing the same thing from c# or f#.  Here’s an example of using f# to print the contents of a List(of T).

 

#light

let l = new ResizeArray<_>()

l.Add(“moe”)

l.Add(“larry”)

l.Add(“curly”)

l.ForEach(fun x -> System.Console.WriteLine(x))

System.Console.Read()

 

ResizeArray is an alias for List(of T) to prevent confusion with the native list in f#.  The type does not have to be supplied, because f# infers it the first time a string is added to the list.

 

So before we get multiline lambda’s, how about we get the single line variety working properly first?

1 comment to Can we please get single line lambda expressions working first?

  • We’re doing both :)

    If you download the CTP that was released at PDC you’ll see you can now type Foo(Sub() Console.Writeline) for lambdas that have void-returning expressions.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>