What is a delegate?
- It is a reference type.
- It is a function pointer or it holds a reference (pointer) to a function (method).
- It is type safe.
- Delegates are mainly used for the event handling and the callback methods.
Explanation
- Let’s create a simple function to display the message, as shown below.
- public static void PrintMessage(string msg)
- {
- Console.WriteLine(msg);
- }
- Now, create a delegate to refer this function, as shown below.
To create a delegate, use the keyword delegate and remaining same as method signature.
public delegate void PrintMsgFunctionDelgate(string Message);
Here, this delegate has return type void and one string parameter. This delegate can be used to point to any function, which has a similar signature i.e., it can be used to point to any function, which has void return type and one string parameter.
- Now, let’s see how we will make this delegate point to the function PrintMessage.
To do this, we have to create an instance of this delegate and this is where a delegate is similar to a class. To create an instance of a delegate, proceed as shown below.
You can see the intellisence is telling that to pass the method name, which is having void return type and the string parameter, the function PrintMessage has the same signature, so I am passing it, as shown below.
PrintMsgFunctionDelgate print = new PrintMsgFunctionDelgate(PrintMessage);
- To invoke that method, all we have to do is to invoke this delegate, as shown below. It is similar like function calls,
This delegate will call PrintMessage function indirectly.
If you are pointing to a function, which has a different signature, you will get a compiler error, as shown below.
In the example given below, my function return type is string and delegate return type is void.
Real time example
Let’s create a class employee
- class Employee
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public int salary { get; set; }
- public float Experiance { get; set; }
-
- public static void PromoteEmp(List<Employee> EmployeeList)
- {
- foreach (Employee emp in EmployeeList )
- {
- if(emp.Experiance>=5)
- {
- Console.WriteLine(emp.Name + " promoted");
- }
- }
- }
- }
Now, I wanted to make this class reusable, but right now it is not. As you can see here, this class has a hard coded condition for promoting employee. Sometimes an employee will be promoted based on salary. For example, whosoever has a salary more than 15,000. In this case, we have to go and edit these hard coded conditions. This is not the right way. We have to change this class, so that without changing the condition inside the class, they can promote the employees there. As per logic, we can use delegate.
Before using delegate, let’s call this class and see how the output will be
- public static void Main()
- {
- List<Employee> empl = new List<Employee>();
- empl.Add(new Employee() { ID = 101, Name = "Ravi", salary = 20000, Experiance = 3 });
- empl.Add(new Employee() { ID = 102, Name = "John", salary = 30000, Experiance = 5 });
- empl.Add(new Employee() { ID = 103, Name = "Mary", salary = 50000, Experiance = 8 });
- empl.Add(new Employee() { ID = 104, Name = "Mike", salary = 10000, Experiance = 2 });
- Employee.PromoteEmp(empl);
- }
The output would be as shown below.
Now, let’s see how this PromoteEmp method inside class makes it reusable, using delegate.
- Create delegate that points to the function, which checks the condition and returns true or false by passing an Employee object, as shown below.
delegate bool isPromote(Employee emp);
- Now, we will replace that, if the condition expression is with that delegate. For this, I am going to pass this delegate as a parameter to the function PromoteEmp and in if condition expression, I am going to call this delegate with an employee object, as shown below.
- public static void PromoteEmp(List<Employee> EmployeeList,isPromote IsEligible)
- {
- foreach (Employee emp in EmployeeList )
- {
- if(IsEligible(emp))
- {
- Console.WriteLine(emp.Name + " Promoted");
- }
- }
- }
Now, you can see that there is no hard coded logic to promote an employee. The logic is used when we call this method.
The logic is written in a separate function, as shown below.
- Public static bool promote(Employee emp)
- {
- if (emp.Experiance >= 5)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
Here, you can write your own logic but it should return true or false.
Passing this logic and promote employee is shown below.
- Creating an instance of delegate
- isPromote pro = new isPromote(promote);
- Calling PromoteEmp function with passing the employee list and the delegate is given below.
- Employee.PromoteEmp(empl, pro);
The full code is given below.
- public static void Main()
- {
- List<Employee> empl = new List<Employee>();
- empl.Add(new Employee() { ID = 101, Name = "Ravi", salary = 20000, Experiance = 3 });
- empl.Add(new Employee() { ID = 102, Name = "John", salary = 30000, Experiance = 5 });
- empl.Add(new Employee() { ID = 103, Name = "Mery", salary = 50000, Experiance = 8 });
- empl.Add(new Employee() { ID = 104, Name = "Mike", salary = 10000, Experiance = 2 });
-
- isPromote pro = new isPromote(promote);
- Employee.PromoteEmp(empl, pro);
- }
-
- public static bool promote(Employee emp)
- {
- if (emp.Experiance >= 5)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
-
- }
-
- delegate bool isPromote(Employee emp);
- class Employee
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public int salary { get; set; }
- public float Experiance { get; set; }
-
-
- public static void PromoteEmp(List<Employee> EmployeeList,isPromote IsEligible)
- {
- foreach (Employee emp in EmployeeList )
- {
- if(IsEligible(emp))
- {
- Console.WriteLine(emp.Name + " Promoted");
- }
- }
- }
- }
There are two types of delegates, which are given below.
- Unicast deligate
This delegate refers to only one method, as shown in the above examples.
- Multicast deligate
This delegate can refer to more than one method. This delegate maintains a list of the methods.
Example,
- delegate void strDele(string str);
- strDele delobj += new strDele (uppercasestr);
- delobj += new strDele (Lowercasestr);
- delobj(“Welcome”);
Note
An instance of a delegate can refer to static as well as instance methods. The signature of function declaration and the delegate declaration should match.