Custom Events in VB .NET 2005

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

This article provides an introduction to Custom Events, a new language feature in VB .NET 2005. Custom Events allow the user to specify what to do when AddHandler, RemoveHandler, and RaiseEvent are called for an event.

Visual Basic 2005 has a number of new language features not present in previous versions of VB.NET. One of these is the ability to create custom events such that the programmer can specify what is done when AddHandler, RemoveHandler and RaiseEvent are called.

Below is an example of VB Code which uses a custom event to log changes to event handling. Of course, this is just one example of how a custom event could be used. The methods could be used for basically any purpose.

Delegate Sub MyDelegate(ByVal message As String)

Class MyClass1
   Custom Event MyEvent As MyDelegate

      ' This code will be run when AddHandler MyEvent, D1
      ' is called
      AddHandler(ByVal value As MyDelegate)
         Console.WriteLine("Adding Handler for MyEvent")
         MyEventHandler = value
      End AddHandler

      ' This code will be run when RemoveHandler MyEvent, D1
      ' is called
      RemoveHandler(ByVal value As MyDelegate)
         Console.WriteLine("Removing Handler for MyEvent")
         MyEventHandler = Nothing
      End RemoveHandler

      ' This code will be run when RaiseEvent MyEvent(string)
      ' is called
      RaiseEvent(ByVal message As String)
         If Not MyEventHandler Is Nothing Then
            MyEventHandler.Invoke(message)
         Else
            Console.WriteLine("No Handler for Raised MyEvent")
         End If
      End RaiseEvent
   End Event

   Public MyEventHandler As MyDelegate

   Public Sub Raise_Event()
      RaiseEvent MyEvent("MyEvent Was Raised")
   End Sub
End Class

Module DelegateModule
   Dim Var1 As MyClass1
   Dim D1 As MyDelegate

   Sub Main()
      Var1 = New MyClass1
      D1 = New MyDelegate(AddressOf MyHandler)
      AddHandler Var1.MyEvent, D1
      Var1.Raise_Event()
      RemoveHandler Var1.MyEvent, D1
   End Sub

   Sub MyHandler(ByVal message As String)
      Console.WriteLine("Event Handled: " & message)
   End Sub
End Module

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read