Delegates

A delegate defines the signature for a particular method (i.e. the parameter list and the return type).
Using delegates allow you to pass functions to and from other functions.
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.
Assigning a method to a delegate creates a delegate instance.


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 2 subroutinse and we want to decide which one to use at run-time.

void DelegateMethod1(string sMessage) { 
    System.Console.WriteLine(sMessage);
}
void DelegateMethod2(string sMessage) {
    System.Console.WriteLine(sMessage);
}

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 void Del_MyDelegate(string sMessage); 

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

Del_MyDelegate1 delMyDelegate; 
delMyDelegate = DelegateMethod1;

Once the delegate has been created this method can then be used within your code.
Invoke is the default method.

delMyDelegate.Invoke("display this message"); 
delMyDelegate("display this message");


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 ))



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