Junior — Middle
Explain the concept of delegates in C# and their main purpose.
sobes.tech AI
Answer from AI
Delegates in C# are types that represent references to methods with a specific signature and return value. They allow storing and invoking methods as objects.
Main purposes of delegates:
- Enable callbacks
- Provide flexibility in method invocation, for example, for events and asynchronous operations handling
- Used to implement event-driven models
Example of a delegate:
// Delegate declaration
public delegate void Notify(string message);
class Program
{
static void Main()
{
Notify notifyHandler = ShowMessage;
notifyHandler("Hello, delegates!");
}
static void ShowMessage(string msg)
{
Console.WriteLine(msg);
}
}
Here, the Notify delegate can reference any method that takes a string and returns void.