Junior — Middle
Have you ever used delegates in your projects or code?
sobes.tech AI
Answer from AI
Yes, delegates in C# are often used to implement callbacks, events, and passing methods as parameters.
A delegate is a type that represents a reference to a method with a specific signature. This allows for dynamic method invocation.
Example of using a delegate:
// Delegate declaration
public delegate void Notify(string message);
class Program
{
static void Main()
{
Notify notify = ShowMessage;
notify("Hello, delegates!");
}
static void ShowMessage(string msg)
{
Console.WriteLine(msg);
}
}
In projects, delegates are useful for event-driven models, such as handling user actions, or for passing logic into methods (e.g., filtering collections).