Introduction
This blog will help beginners understand the concept of delegates, their types, and their actual implementation, in the simplest possible way.
What are Delegates?
Delegates are the pointers to function. It defines what a function looks like.
Types of Delegate
- Simple Delegate
- Multicast Delegate
- Generic Delegate
- Func
- Action
- Predicate
Simple Delegate
public delegate int MyDeleate(int a, int b);
We can create a delegate using the keyword delegate. The above delegate can hold the reference of any method which has two int parameters and returns int.
Let’s do some code!
- public class Math
- {
- public int Add(int a, int b)
- {
- return (a + b);
- }
- }
- static void Main(string[] args) {
- Math m = new Math();
- //Create object of Delegate. Provide method name as parameter
- MyDeleate mydelegate = new MyDeleate(m.Add);
- //Call Delegate
- var result = mydelegate(10, 20);
- Console.WriteLine(result);
- }
We can, then, call the delegate similarly as we call any method.
Multicast Delegate
Multicast Delegates can point to multiple methods. Once delegate objects are created, we can play with them.
Let’s take an example.
- public delegate void FunDelegate(); //Delegate
- static void Main(string[] args)
- {
- Fun f = new Fun();
- FunDelegate fun1 = new FunDelegate(f.PrintHi);
- FunDelegate fun2 = new FunDelegate(f.PrintBye);
- FunDelegate fun3;
- FunDelegate fun4;
- FunDelegate fun5;
- fun3 = fun1 + fun2; //Multicast Delegate
- fun4 = fun1 - fun2; //Multicast Delegate
- fun5 = fun2 - fun1; //Multicast Delegate
- Console.WriteLine("----- Calling fun1----");
- fun1();
- Console.WriteLine("----- Calling fun2----");
- fun2();
- Console.WriteLine("----- Calling fun3----");
- fun3();
- Console.WriteLine("----- Calling fun4----");
- fun4();
- Console.WriteLine("----- Calling fun5----");
- fun5();
- Console.ReadKey();
- }
- class Fun
- {
- public void PrintHi() {
- Console.WriteLine("Hi");
- }
- public void PrintBye() {
- Console.WriteLine("Bye");
- }
- }
The output of the above code would be:

Generic Delegate

Dhiraj GhodePosted Aug 4, 2016, 9:07 AM
Very well understood with simple example.
Sagar ChavanPosted Aug 1, 2016, 3:09 AM
Nice blog specially Multicast delegate