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
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
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.
For declaring delegates following syntax is used
After declaring delegates objects are instanced with new keyword.
Syntax for instantiating delegates
Example
Output: