dotnet / vblang

The home for design of the Visual Basic .NET programming language and runtime library.
289 stars 66 forks source link

Use + for multicast delegates #317

Open ghost opened 6 years ago

ghost commented 6 years ago

I have this delegate: Delegate Sub MsgSub(ByVal Msg As String)

suppose I have two subs Show1 and show2, then I can do:

Dim M As MsgSub = [Delegate].Combine(New MsgSub(AddressOf Show1), 
                  New MsgSub(AddressOf Show2))

In C# this can be done by using + operator directly, so why can't VB.NET allow this:

Dim M As MsgSub = New MsgSub(AddressOf Show1)+ New MsgSub(AddressOf Show2)

Furthermore, I want to do this directly:

Dim M As MsgSub = AddressOf Show1 + AddressOf Show2
rskar-git commented 6 years ago

Would something like this be helpful?:

Module VbDelegate
    <Extension>
    Public Function Add(ByRef d0 As [Delegate], d1 As [Delegate]) As [Delegate]
        d0 = [Delegate].Combine(d0, d1) : Return d0
    End Function
    <Extension>
    Public Function Add(ByRef d0 As [Delegate], d() As [Delegate]) As [Delegate]
        Dim result As [Delegate] = d0
        For i As Integer = 0 To d.Count - 1
            result = [Delegate].Combine(result, d(i))
        Next
        d0 = result
        Return result
    End Function
    <Extension>
    Public Function Combine(d() As [Delegate]) As [Delegate]
        Dim result As [Delegate] = d(0)
        For i As Integer = 1 To d.Count - 1
            result = [Delegate].Combine(result, d(i))
        Next
        Return result
    End Function
End Module

Dim M As MsgSub = New MsgSub() {
    AddressOf Show1, AddressOf Show2, AddressOf Show3
    }.Combine()

M.Add(New MsgSub(AddressOf Show4))
M.Add(New MsgSub() {AddressOf Show5, AddressOf Show6})
ghost commented 6 years ago

@rskar-git It is a possible workarround. But it is better to make VB.NEt and C# as close as possible, so we can esily read and convert code of any of them. Thanks.

KathleenDollard commented 6 years ago

AddHandler does [Delegate].Combine under the covers when you are adding two handlers to the event.

Combining two delegates, except in event handling is an uncommon operation.

We don't see the need for this as being sufficient to add a feature.