The delegate is a pointer that allows the call of a function indirectly through its memory address. The delegate is used to call methods of other objects. It is similar to the function pointer used in other programming languages. The difference is that the delegate is a reference type on System.Delegate class.
Delegates are useful in situations where the occurrence of a specific event call different event handlers, depending on the context of the event occurrence. This requires dynamic association of events with event handlers, the delegates being used for this purpose.
Declaring an event with Event specification leads to defining of an default delegate class called EventHandler inside the class that defined event.
AddressOf specification creates a default instance of the delegate.
AddHandler ObEveniment.UnEveniment, _
New EventHandler(AddressOf ObEveniment_HandlerEveniment)
An event can be declared using a delegate type previously created.
Delegat Sub TipDelegat()
Event EvenimentDoi As TipDelegat
This allows the association of several events with the same event handler.
Delegates can be used to call different versions of subroutines, depending on the context of application execution.
Invoking delegate method involves:
- Creating delegate;
- Declaring the class thet contains the delegate method with the same signature (parameter list);
- Creating delegate instance and invoking the method associated with the delegate by calling the default method Invoke.
The below example shows mechanisms for defining and using delegates. The application type selected to define the project is Console Application.
'creating a delegate
Delegate Sub DelOpAritmetica(ByVal x As Integer, ByVal y As Integer)
'creating first class containing
'a method with the same signature as the delegate
Class GrupOp1
Sub OpDiferenta(ByVal a As Integer, ByVal b As Integer)
Dim dif As Integer
dif = a - b
MsgBox("Difference is: " & CStr(dif))
End Sub
End Class
'creating the second class containing
'a method with the same signature as the delegate
Class GrupOp2
Sub OpInmultire(ByVal a As Integer, ByVal b As Integer)
Dim prod As Integer
prod = a * b
MsgBox("Multiplication value is: " & CStr(prod))
End Sub
End Class
Sub Main()
'defining an object variable of GrupOp1 type
Dim op1 As New GrupOp1
'defining an object variable of GrupOp2 type
Dim op2 As New GrupOp2
'creating an instance of the delegate
Dim del As DelOpAritmetica
'initiliazation of the instance for the delegate with the address
'of the method OpDiferenta defined in GrupOp1 class
del = AddressOf op1.OpDiferenta
'invoking the method OpDiferenta through delegate
del.Invoke(10, 3)
'initialization of the instance for the delegate with address
'of the method OpInmultire defined in GrupOp2 class
del = AddressOf op2.OpInmultire
'invoking the method OpInmultire through delegate
del.Invoke(9, 3)
End Sub
Thanks for clear and concise explanation.