Delgates are similar to a function pointer in C language.
A delegate is an object which stores the reference/address of a function.
A delegate can hold the reference of only those functions whose signature matches with that of a function.
Syntax:
<accessModifier> delegate <datatype> <nameofdelegate>(<arg1>,<arg2>)
There are 2 types of delegates:
- Unicast delegate
- Multicast delegate
1. Unicast delegate holds the reference of one function.
Example:
- using System;
- namespace unicast
- {
- public delegate int AddDelegate(int x, int y);
-
- class program
- {
- static void Main()
- {
- AddDelegate dlg = new AddDelegate(Add);
- int r = dlg.Invoke(10, 20);
- Console.WriteLine("Sum is {0}", r);
- Console.ReadKey();
- }
- public static int Add(int x, int y)
- {
- return (x + y);
- }
- }
- }
Output:
Sum is 30
2.
- Multicast delegate multicast delegate holds the reference of more than one function.
- Return type should be void.
Example:
- using System;
- namespace multicast
- {
- public delegate void AddDelegate(int x, int y);
-
- class program
- {
- static void Main()
- {
- AddDelegate dlg = new AddDelegate(Add);
- dlg = dlg + new AddDelegate(Substract);
- dlg.Invoke(10, 20);
-
- Console.ReadKey();
- }
- public static void Add(int x, int y)
- {
- Console.WriteLine ("Sum is {0}",(x+ y));
- }
- public static void Substract(int x, int y)
- {
- Console.WriteLine("Difference is {0}", (x - y));
- }
- }
- }
Output:
Sum is 30
Difference is -10