Sobes.tech
Middle+

What are delegates?

sobes.tech AI

Answer from AI

Delegates in C# are types that represent references to methods with a specific signature and return type. They allow passing methods as parameters, storing them in variables, and invoking them dynamically. This is the basis for events and callbacks.

Example of a delegate:

// Delegate declaration
public delegate int Operation(int x, int y);

class Program
{
    static int Add(int a, int b) => a + b;
    static int Multiply(int a, int b) => a * b;

    static void Main()
    {
        Operation op = Add;
        Console.WriteLine(op(3, 4)); // 7

        op = Multiply;
        Console.WriteLine(op(3, 4)); // 12
    }
}

Thus, delegates provide flexibility and extensibility to the code, allowing dynamic selection and invocation of methods.

What are delegates? — C# - sobes.tech