Understanding Delegates
March 15, 2023
A delegate is a type in C# that represents a reference to a method. It allows you to pass methods as arguments to other methods or assign them to variables. Here’s a simple example to demonstrate how a delegate works:
using System; delegate int MyDelegate(int x, int y); class Program { static int Add(int x, int y) { return x + y; } static int Multiply(int x, int y) { return x * y; } static void Main(string[] args) { // create delegate instances MyDelegate addDelegate = new MyDelegate(Add); MyDelegate multiplyDelegate = new MyDelegate(Multiply); // use delegate instances to call the methods int result1 = addDelegate(5, 3); // returns 8 int result2 = multiplyDelegate(5, 3); // returns 15 // output the results Console.WriteLine($"Add: {result1}"); Console.WriteLine($"Multiply: {result2}"); } }
In this example, we first define a delegate type MyDelegate that takes two integers as parameters and returns an integer. Then, we define two static methods Add and Multiply that match the delegate signature.
In the Main method, we create two delegate instances addDelegate and multiplyDelegate that reference the Add and Multiply methods respectively. We then use these delegate instances to call the methods and store the results in result1 and result2. Finally, we output the results to the console.
By using delegates, we can pass methods as arguments to other methods, allowing for greater flexibility and extensibility in our code.