Sobes.tech
Junior

Provide an example of using delegates in C#.

sobes.tech AI

Answer from AI

Delegates are type-safe pointers to methods. They allow passing methods as arguments, assigning them to variables, and invoking them through these variables. Delegates are widely used for creating events, callbacks, and asynchronous programming.

Example of using a delegate:

  1. Declaring a delegate: Define the signature of the method that the delegate can point to.
public delegate int MyDelegate(int x, int y);
  1. Defining methods: Create methods with a signature that matches the delegate.
public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Subtract(int a, int b)
    {
        return a - b;
    }
}
  1. Using the delegate: Create an instance of the delegate and assign a method to it. Then invoke the method through the delegate.
public class Program
{
    public static void Main(string[] args)
    {
        Calculator calc = new Calculator();

        // Create a delegate instance and assign the Add method
        MyDelegate del = new MyDelegate(calc.Add);

        // Call the Add method via the delegate
        int result1 = del(10, 5); // result1 = 15
        Console.WriteLine($"Sum result: {result1}");

        // Reassign the delegate to the Subtract method
        del = calc.Subtract;

        // Call the Subtract method via the delegate
        int result2 = del(10, 5); // result2 = 5
        Console.WriteLine($"Subtraction result: {result2}");
    }
}

In this example, MyDelegate can point to any method that takes two integer arguments (int x, int y) and returns an integer (int). We create two delegate instances (del), assign them the Add and Subtract methods respectively, and then use the delegate to invoke these methods.

Provide an example of using delegates in C#. — C# - sobes.tech