Delegates can be defined as an object refer to a methods or we can say that
it is a referenced type variable that holds the reference of a method. It is similar to pointer function in C and C++, but is
object-oriented, secure and type safe than function pointer. It is used for implementing events and call back methods. For example, if we click on Button on forms (windows application), then program would call a specific method or it is a type reference to a method with particular parameter list and return type and then calls methods when it is needed. All delegates are implicitly derived from System.Delegates class.
using System;
delegate int NumberChanger(int n); namespace DelegateAppl {
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
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(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();
}
}
}
Output:
Value of Num: 35
Value of Num: 175
Liked By
Write Answer
Give a detailed explanation of Delegates in C#
Join MindStick Community
You have need login or register for voting of answers or question.
Nishi Tiwari
13-Dec-2019Delegates can be defined as an object refer to a methods or we can say that it is a referenced type variable that holds the reference of a method. It is similar to pointer function in C and C++, but is object-oriented, secure and type safe than function pointer. It is used for implementing events and call back methods. For example, if we click on Button on forms (windows application), then program would call a specific method or it is a type reference to a method with particular parameter list and return type and then calls methods when it is needed. All delegates are implicitly derived from System.Delegates class.
For declaring delegates following syntax is used
After declaring delegates objects are instanced with new keyword.
Syntax for instantiating delegates
Example
Output: