Introduction
Delegates are not necessary but we use them to improve the security of the class data member function. Delegates are more useful when we need to hide the actual name of the function before going in detail that what delegates are, I want to explain why there are delegates.
Need of delegates
Whenever we want to make our methods more secure we can create a delegate and make our methods more secure. Even we can access the private member function without using their name with the help of delegates.
What are delegates
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance. It is similar to C/C++ pointer to function.
Syntax to create delegate
[Access specifier] delegate [return type] name of the delegate (parameter list).
Here,
- Access specifier - indicates the accessibility of delegate.
- Delegate - it’s a keyword that defines the delegate.
- name of the delegate - here we write the name of the delegate.
- parameter list - here we pass the parameter that match with signature of the function.
Example
public delegate int PerformCalculation(int x, int y);
explanation
This delegate can call any method that matches its signature means that return type and parameters must be same in both delegate and function, we have to just pass the function to the delegate.
How to use delegates
We can simply assign method to the delegate by creating an object of delegate and assigning function to them
Let’s have a look,
- Delegate name object_naame = new Delegate name(function name);
- Next we can call the function with the object of the delegate
- object_naame(parameter);// calling the method without using the name of the method
Example
using System;
delegate int numMath(int n);
namespace delegates {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
numMath nc1 = new numMath(AddNum);
numMath nc2 = new numMath(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

Join the conversation! Your thoughts help the community grow.