Junior — Middle
What is the role and purpose of delegates in programming?
sobes.tech AI
Answer from AI
Delegates in programming, especially in C#, are types that represent references to methods with a specific signature and return type. They allow storing and invoking methods as objects.
Main purposes of delegates:
- Enable callbacks.
- Used for events and event handling.
- Provide flexibility and extensibility of code by allowing methods to be passed as parameters.
Example of using a delegate:
// Delegate declaration
public delegate int Operation(int x, int y);
// Methods matching the delegate
public int Add(int a, int b) => a + b;
public int Multiply(int a, int b) => a * b;
// Using the delegate
Operation op = Add;
int result = op(3, 4); // result = 7
op = Multiply;
result = op(3, 4); // result = 12
Thus, delegates allow dynamically selecting and invoking methods, which is convenient for event-driven models and functional programming.