Delegates

A delegate defines the signature for a particular method (i.e. the parameter list and the return type).
This delegate can then be used to refer to any object or variable with the same signature.
Delegates give you a way of calling methods which are only known at run time.
A delegate is a reference type that represents a method with a specific signature and return type.
These allow you to specify methods at run-time.


Why are Delegates useful ?

Event Handlers are implemented as delegates.
A delegate can refer to a regular subroutine or function in a module.
A delegate can refer to a shared subroutine or function in a class.
A delegate can refer to an instance procedure.
All .NET events are internally implemented through delegates.


Defining a Delegate

Lets suppose that we have the following two subroutines and we want to decide which one to use at run-time.

Sub DebugMsg(ByVal sMessage As String) 
   Debug.WriteLine(sMessage)
End Sub

Sub PopUpMsg(ByVal sMessage As String)
   Microsoft.VisualBasic.MsgBox(sMessage)
End Sub

You must first declare a Delegate with an identical signature.
This delegate can be used to refer to any method that accepts a String argument.

Public Delegate Sub Del_MyDelegate(ByVal sMessage As String) 

At run-time you can create an instance of this delegate passing in the corresponding method name.

Dim delMyDelegate = New Del_MyDelegate(AddressOf DebugMsg) 

Once create this method can then be used within your code.

delMyDelegate.Invoke("display this message") 
delMyDelegate("display this message") 'since Invoke is the default

If you then want to change the subroutine which is called you just need to change the definition of the delegate:

Dim delMyDelegate = New Del_MyDelegate(AddressOf PopMsg) 

Example

Lets suppose you wanted to create a simple container class called Pair that can hold and sort any two objects passed to it.
You don't know in advance what kind of objects it will hold, but it is possible to create methods within those objects which the sorting task can be delegated to.
This problem is solved by delegating this responsibility to the objects themselves.
Our pair class no longer needs to know how the objects are sorted; it just needs to know that they can be sorted.
The pair container needs to specify the method these objects must implement.
Rather than specifying a particular method name, the pair needs to specify the signature and the return type.
(( you can call your delegate methods anything you like ))



© 2019 Better Solutions Limited. All Rights Reserved. © 2019 Better Solutions Limited TopPrevNext