views:

111

answers:

1

Is it possible to translate the following C# code into VB.NET, using VB 9.0?

delegate Stream StreamOpenerDelegate(String name);

void Exec1()
{
    WorkMethod( x => File.OpenRead(x));
}

void Exec2()
{
    StreamOpenerDelegate opener = x => return File.OpenRead(x) ;
    WorkMethod(opener);
}

Can I do something like this?:

Private Delegate Function StreamOpenerDelegate(ByVal name As String) As Stream

Private Sub WorkMethod(ByVal d As StreamOpenerDelegate)
    ''
End Sub

Private Sub Exec1()
    Me.WorkMethod(Function (ByVal x As String) 
        Return File.OpenRead(x)
    End Function)
End Sub

Private Sub Exec2()
    Dim opener As StreamOpenerDelegate = Function (ByVal x As String) 
        Return File.OpenRead(x)
    End Function
    Me.WorkMethod(opener)
End Sub

I'm trying to write some documentation, but I don't know VB syntax. Often I use Reflector to translate it, but I'm not sure it's working in this case. I'm also not clear on where I would need line continuation characters.


ANSWER
In VB9, it's not possible to have multi-line lambdas (or Sub lambdas, which I did not ask about). In VB9, all lambdas return a value, and must be a single expression. This changes in VB10. VB10 will allow the above syntax, but VB9 will not. In VB9, if the logic involves multiple code lines, it must not be a lambda; you must put it into a named Function and reference it explicitly. Like this:

Private Delegate Function StreamOpenerDelegate(ByVal name As String) As Stream

Private Sub WorkMethod(ByVal d As StreamOpenerDelegate)
    ''
End Sub

Function MyStreamOpener(ByVal entryName As String) As Stream
    '' possibly multiple lines here
    Return File.OpenRead(entryName)
End Function

Private Sub Exec1()
    Me.WorkMethod(AddressOf MyStreamOpener)
End Sub

cite: Mike McIntyre's blog

+2  A: 

This should work:

Private Sub Exec1()
    Me.WorkMethod(Function (x) File.OpenRead(x))
End Sub

Private Sub Exec2()
    Dim opener As StreamOpenerDelegate = Function (x) File.OpenRead(x)

    Me.WorkMethod(opener)
End Sub

You need the line continuation character to split a single line statement into multiple lines, like so:

Private Sub Exec1()
    Me.WorkMethod(Function (x) _
                    File.OpenRead(x))
End Sub

Private Sub Exec2()
    Dim opener As StreamOpenerDelegate = Function (x) _
                                           File.OpenRead(x)

    Me.WorkMethod(opener)
End Sub

In any case, in VS2010 there is implicit line continuation after certain characters. So I wouldn't worry about it too much.

Yannick M.