This post was most recently updated on April 25th, 2019
What is delegate?
- It is reference to a method inside delegate object
- User defined type
- It is not member of class but similar to class
When to use delegate?
- Represent or refer more than one functions
- Used to define call back methods
- In order to use delegate it is necessary to create an object to delegate
Types of delegate?
- Single cast delegate: represents or refer only one function
- Multicast delegate: represents or refer more than one function
Steps in working with delegate:
- Creating a delegate
- Instantiating a delegate
- Invoking a delegate
Creating a delegate:
Syntax
access modifier delegate return type Delegate name ([arguments list]);
Public delegate void Delegate (int x, int y);
Note: While creating delegate its return type,number of arguments and its data types should be same as function that we want to refer to.
e.g
1 2 3 |
Public void Add(int a, int b) { Code….. } |
If we want to use delegate to refer above function then it should be declared like:
1 |
Public delegate void my_Delegate (int x, int y); |
Example of single cast delegate:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DelegatesDemo { class Program { static void Display(string S) { Console.WriteLine("My Name is :" + S); } delegate void X(string a); static void Main(string[] args) { X objD = new X(Display); objD("Rathrola Prem Kumar"); Console.Read(); } } } |
Multi cast delegate:
In multi cast delegate to add reference to more than one function use operator (+=)
1 2 |
objD += obj1.substract; objD += obj1.Add; |
And to remove the reference of any function from delegate object use operator (-=)
1 |
objD -= obj1.substract; |
Example of Multi cast delegate:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DelegatesDemo { class Program { public void Add(int x, int y) { Console.WriteLine("Sum is:" + (x + y)); } public void Substract(int x, int y) { Console.WriteLine("Difference is:" + (x - y)); } } public delegate void MultiCastDelegate(int a, int b); class ClsDelegate { static void Main() { Program obj1 = new Program(); MultiCastDelegate objD = new MultiCastDelegate(obj1.Add); objD += obj1.Substract; objD(40, 10); objD -= obj1.Substract; objD(50, 10); Console.ReadLine(); } } } |
o/p of above code: