Export (0) Print
Expand All

Delegates and the AddressOf Operator

Delegates are objects you can use to call the methods of other objects. They are sometimes described as type-safe function pointers because they are similar to function pointers used in other programming languages. But unlike function pointers, Visual Basic .NET delegates are a reference type based on the class System.Delegate, and can reference both shared methods — methods that can be called without a specific instance of a class — and instance methods.

Delegates are useful in situations where you need an intermediary between a calling procedure and the procedure being called. For example, you might want an object that raises events to be able to call different event handlers under different circumstances. Unfortunately, the object raising events cannot know ahead of time which event handler is handling a specific event. Visual Basic .NET lets you dynamically associate event handlers with events by creating a delegate for you when you use the AddHandler statement. At run time, the delegate forwards calls to the appropriate event handler.

Although you can create your own delegates, in most cases Visual Basic .NET creates the delegate and takes care of the details for you. For example, an Event statement implicitly defines a delegate class named <EventName>EventHandler as a nested class of the class containing the Event statement, and with the same signature as the event. The AddressOf statement implicitly creates an instance of a delegate. For example, the following two lines of code are equivalent:

AddHandler Button1.Click, AddressOf Me.Button1_Click
   ' The previous line of code is shorthand for the next line of code.
AddHandler Button1.Click, New EventHandler(AddressOf Button1_Click)

You can use the shorthand way of creating delegates anywhere the compiler can determine the delegate's type by the context.

Declaring Events that Use an Existing Delegate Type

In some situations, you may want to declare an event to use an existing delegate type as its underlying delegate. The following syntax demonstrates how:

Event AnEvent As DelegateType

This is useful when you want to route multiple events to the same handler.

See Also

Delegate Statement | AddressOf Operator | Events and Event Handlers | AddHandler and RemoveHandler | Writing Event Handlers | Multithreaded Applications

Show:
© 2014 Microsoft