Custom Event - invokation list implementation considerations

Posted by M.A. Hanin on Stack Overflow See other posts from Stack Overflow or by M.A. Hanin
Published on 2010-04-09T16:03:50Z Indexed on 2010/04/10 10:13 UTC
Read the original article Hit count: 566

I'm looking for some pointers on implementing Custom Events in VB.NET (Visual Studio 2008, .NET 3.5).

I know that "regular" (non-custom) Events are actually Delegates, so I was thinking of using Delegates when implementing a Custom Event. On the other hand, Andrew Troelsen's "Pro VB 2008 and the .NET 3.5 Platform" book uses Collection types in all his Custom Events examples, and Microsoft's sample codes match that line of thought.

So my question is: what considerations should I have when choosing one design over the other? What are the pros and cons for each design? Which of these resembles the inner-implementation of "regular" events?

Below is a sample code demonstrating the two designs.

Public Class SomeClass
    Private _SomeEventListeners As EventHandler
    Public Custom Event SomeEvent As EventHandler
        AddHandler(ByVal value As EventHandler)
            _SomeEventListeners = [Delegate].Combine(_SomeEventListeners, value)
        End AddHandler

        RemoveHandler(ByVal value As EventHandler)
            _SomeEventListeners = [Delegate].Remove(_SomeEventListeners, value)
        End RemoveHandler

        RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
            _SomeEventListeners.Invoke(sender, e)
        End RaiseEvent
    End Event

    Private _OtherEventListeners As New List(Of EventHandler)
    Public Custom Event OtherEvent As EventHandler
        AddHandler(ByVal value As EventHandler)
            _OtherEventListeners.Add(value)
        End AddHandler

        RemoveHandler(ByVal value As EventHandler)
            _OtherEventListeners.Remove(value)
        End RemoveHandler

        RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
            For Each handler In _OtherEventListeners
                handler(sender, e)
            Next
        End RaiseEvent
    End Event
End Class

© Stack Overflow or respective owner

Related posts about vb.net

Related posts about custom-events