ProgrammingVB.NET Developer

How to implement event handling and delegates in Visual Basic, and how does the usage scenario differ for standard and custom events?

Pass interviews with Hintsage AI assistant

Answer.

In Visual Basic (VB.NET), delegates are types that contain a reference to a method with a specific signature and serve as the basis for event handling. Events are built on delegates, allowing objects to notify others of changes that have occurred.

For standard events, predefined delegates are used, such as EventHandler, whereas for custom events, you can define your own delegate with the desired signature:

'Declaration of custom delegate and event Public Delegate Sub ChangedEventHandler(sender As Object, e As EventArgs) Public Event Changed As ChangedEventHandler 'Using the event Public Sub OnChanged() RaiseEvent Changed(Me, EventArgs.Empty) End Sub

Nuances:

  • An event can only be raised within the class where it is declared;
  • Delegates can be combined to create a chain of calls;
  • Failure to comply with the correct signature results in compilation errors.

Trick Question.

Why can't an event in Visual Basic be raised outside the class, even if it is declared as Public?

Answer: Despite the Public access modifier, an event can only be "subscribed" or "unsubscribed" from outside the class, but it can only be raised (RaiseEvent) within the confines of the class — this is a language-specific feature that ensures encapsulation and control over event dispatching. For example:

Public Class Foo Public Event MyEvent() End Class Dim f As New Foo() ' This cannot be done: f.RaiseEvent MyEvent() — the compiler will not allow this.

Examples of real errors due to ignorance of the nuances of the topic.


Story

Windows Forms Project: A developer attempted to raise the "DataUpdated" event from outside the data class to update the UI. It failed, the event was not handled, and the architecture had to be refactored, reworking the logic due to a misunderstanding of event visibility.


Story

Web Service: When declaring the delegate, one variable in the signature was omitted. The event was subscribed to, but it was called with a runtime error — the subscriber expected one argument, but the call was made with two.


Story

1C Plugin: Developers used FieldInfo.SetValue to simulate raising the event. This caused a mismatch in the interface state and a crash during assembly updates.