In this article we will try to understand what is delegate, how to use it.
Dictionary meaning: “A person sent or authorized to represent others “or “A person designated to act for or represent another or others”
History of Delegate in C#
The diagram shows the history of delegates by C# version,
A delegate is a class that can hold a reference (source of information) to a method. We can say that delegate is like a pointer to a function.
Every delegate object is implicitly derived from class Delegate.
Declaration of Delegate:
A delegate can be declared using delegate keyword followed by a function signature as shown below:
Signature of a Single Cast Delegate:
delegate (< parameter list >)
Example:
public delegate void myDelegate(string myMessage);
Delegate class has four steps process for defining and using delegates – Declaration, Reference, Target and Invoke.
The first step is to declare the delegate with the return type and input parameters.
// Delegates declaration public delegate int myDelegate(int a, int b);
Which is having same signature as method below.
public int Sum(int a, int b) { return a + b; }
The Second step is to create a delegate reference.
// Create delegate reference DelegateClass.myDelegate objSum = null;
The third step is to target/point the delegate reference to an object instance.
// Target the reference to the Sum method objSum = objMyclass.Sum;
The final step is to invoke the delegate, like as invoking a regular method.
// Invoke the delegate Console.WriteLine("Sum of two integer is = " + objSum(10, 20)); Console.ReadLine();
Finally the Sample Code:
namespace DelegatesProperties { class DelegateClass { // Delegates declaration public delegate int myDelegate(int a, int b); // Methods to Target & called by delegate public int Sum(int a, int b) { return a + b; } } class Program { static void Main(string[] args) { DelegateClass objMyclass = new DelegateClass(); // Create delegate reference DelegateClass.myDelegate objSum = null; // Target/Point the reference to the Sum method objSum = objMyclass.Sum; // Invoke the delegate if (objSum != null) { Console.WriteLine("Sum of two integer is = " + objSum(10, 20)); Console.ReadLine(); } } } }
Output: Sum of two integer is 30;
Let’s do it with Anonymous Method:
namespace DelegateAnonymous { class DelegateClass { // Delegates declaration public delegate int myDelegate(int a, int b); } class Program { static void Main(string[] args) { DelegateClass objMyclass = new DelegateClass(); // Create delegate reference DelegateClass.myDelegate objSum = null; // Point the reference to the Sum method objSum = delegate (int a, int b) // Anonymous Method { return a + b; }; // Invoke the delegate //objSum.Invoke(20, 10); if (objSum != null) { Console.WriteLine("Sum of two integer is = " + objSum(10, 20)); Console.ReadLine(); } } } }
Output will be the same as before, this time we have made a little bit change to point the method.Here we use an annymous method, let’s take a look how:
objSum = delegate (int a, int b) // Anonymous Method { return a + b; };
And the Sum method is no more exist in the DelegateClass
public int Sum(int a, int b) { return a + b; }
Types of delegates:
- Single cast delegate
- Multi cast delegate
Single Cast Delegate:
A single cast delegate holds the reference of only single method. This type of delegate is derive from the System.Delegate class.
Note: Our previous Example is a single cast delegate
Multi Cast Delegate:
The delegate can points to multiple methods. Class MulticastDelegate derives from Delegate and represents a delegate that can invoke more than one method at once.
Internally, MulticastDelegate is implemented as a linked list of delegates.
Add/Remove Delegates:
All delegate types declared in C# have implicit operators += and -=. The “+” operator adds a function to the delegate object and the “-” operator removes an existing function from a delegate object.
Sample Example:
namespace MulticastDelegates { class DelegateClass { // Delegates declaration public delegate void myDelegate(int a, int b); // Methods to Target & called by delegate public void Sum(int a, int b) { Console.WriteLine("Sum of two integer is = " + (a + b)); } public void Divide(int a, int b) { Console.WriteLine("Divide of two integer is = " + (a / b)); } public void Multiply(int a, int b) { Console.WriteLine("Multiply of two integer is = " + (a * b)); } } class Program { static void Main(string[] args) { DelegateClass objMyclass = new DelegateClass(); // Create delegate reference DelegateClass.myDelegate objSum = null; // Point the reference to the Sum method objSum += objMyclass.Sum; objSum -= objMyclass.Divide; objSum += objMyclass.Multiply; // Invoke the delegate if (objSum != null) { objSum(20, 5); Console.ReadLine(); } } } }
Output:
Sum of two integer is 25;
Divide of two integer is 4; not showing this time.
Multiply of two integer is 100;
Key Notes:
- Delegates are reference type.
- Delegates are type-safe.
- Delegates encapsulates one or more methods.
- We can invoke all the methods the delegate is encapsulating with a single call
- Delegates allow methods to be passed as parameters.
- Invoking a delegate is like as invoking a regular method.
- Delegates are used in event handling for defining callback methods.
- Once a delegate is created, the method it is associated will never changes because delegates are immutable in nature.
- Delegates provide a way to execute methods at run-time.
- All delegates are implicitly derived from System.MulticastDelegate, class which is inheriting from System.Delegate class.
Nirmal says:
objSum = objMyclass.Sum;
can you tell me what is “objMyclass” here?