In Visual Basic, events (Events) allow an object to notify other components of the application about changes that have occurred. An event is declared using the Event keyword. It is raised using the RaiseEvent method (VB.NET) or Raise (VB6), and components can subscribe to it (Handles/WithEvents).
Example VB.NET:
Public Class Worker Public Event WorkCompleted As EventHandler Public Sub DoWork() ' ...some work RaiseEvent WorkCompleted(Me, EventArgs.Empty) End Sub End Class Public Class Manager Private WithEvents w As Worker Public Sub New() w = New Worker() End Sub Private Sub w_WorkCompleted(sender As Object, e As EventArgs) Handles w.WorkCompleted Console.WriteLine("Work completed!") End Sub End Class
Important Points:
WithEvents can only be used with fields and properties of a class.Can an event be declared with the access modifier
Privateand subscribed to from another class?
Answer: No, the Private modifier restricts the visibility of the event only to the class where it is declared. Other classes will not see it and therefore cannot subscribe.
Story
In a large application, events were created with the
Publicmodifier but were never explicitly unsubscribed from. During long application runs, this led to memory leaks as handlers referenced unnecessary objects.
Story
In the migration from VB6 to VB.NET, the developer expected the event to be available in all modules, but by default, the event was
Friend. As a result, the handler did not trigger, and this bug was found only during integration testing.
Story
A programmer made a mistake in the event delegate signature - swapped
senderande. There were no error messages (the event handler simply was not called), and the necessary business logic was silently skipped until the penultimate release.