A delegate is a type that represents a pointer to a method. A delegate type defines the parameters and return type of the kind of method that it can point to. Then, a delegate instance can be constructed around the address of any compatible method. A delegate instance can be invoked just as if it were a subroutine, and it will call the method that the delegate points to. For example, the following code creates a delegate instance that points to the method Class1.S1 and then invokes it. Delegate Sub SubroutineDelegate(ByVal x As Integer) Class Class1 Public Sub S1(ByVal x As Integer) MsgBox(x) End Sub End Class Module Test Sub Main() Dim s1 As SubroutineDelegate Dim t As New Class1() s1 = New SubroutineDelegate(AddressOf t.S1) s1(10) End Sub End Module A delegate instance stores both the address of the method and the instance given when the delegate was created (if the method is not shared). Delegates can be multicast , which means that multiple delegates can be combined into a single delegate that will invoke all the methods , one at a time. The following example creates a delegate that points to both Class1.S1 and Class1.S2 . When the delegate is invoked, each method will be invoked in turn . Delegate Sub SubroutineDelegate(ByVal x As Integer) Class Class1 Public Sub S1(ByVal x As Integer) MsgBox("S1: " & x) End Sub Public Sub S2(ByVal x As Integer) MsgBox("S2: " & x) End Sub End Class Module Test Sub Main() Dim s1, s2 As SubroutineDelegate Dim t As New Class1() s1 = New SubroutineDelegate(AddressOf t.S1) s2 = New SubroutineDelegate(AddressOf t.S2) s1 = [Delegate].Combine(s1, s2) s1(10) End Sub End Module |