Junior — Middle
Can you explain the concept of delegates and their role in programming?
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.
Role of delegates:
- Enable callbacks.
- Used for events and event handling.
- Provide flexibility and extensibility of code.
Example of using 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 allow dynamic selection and invocation of methods.