C# delegates are similar to pointers to functions, in C or C++. Adelegateis a reference type variable that holds the reference to a method. The reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from theSystem.Delegateclass.
using System;
delegate int ReplaceNumber(int n); namespace DelegateApp { class UseDelegate { static int number = 10; public static int AddNumber(int p) { number += p; return number; }
public static int MultNumber(int q) { number *= q; return number; } public static int getNumber() { return number; }
static void Main(string[] args) { //create delegate instances ReplaceNumber numberc1 = new ReplaceNumber(AddNumber); ReplaceNumber numberc2 = new ReplaceNumber(MultNumber);
//calling the methods using the delegate objects numberc1(25); Console.WriteLine("First Value of Number: {0}", getNumber()); numberc2(5); Console.WriteLine("Second Value of Number: {0}", getNumber()); Console.ReadKey(); } } }
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.
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.