Basically delegates in c# are type safe objects which are used to hold reference of one or more methods in c#.net.
Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.
Example
public delegate int DelegateExample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
DelegateExample delgat1 = sc.Add;
int i = delgat1(5, 5);
Console.WriteLine(i);
DelegateExample delgat2 = sc.Sub;
int j = delgat2(5, 2);
Console.WriteLine(j);
}
}
Output
Add Result : 10
Sub Result : 3
Use of Delegates
if we have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.
Delegate's Types:
1. Single and Multi Caste Delegate