- What is a Delegate?
- Declaring and Using a Delegate
- Multicast Delegate
- Delegate with Lambda Expressions
- Conclusion
What is a Delegate?
In C#, a delegate is a special type that represents references to methods. You can think of it like a function pointer in C/C++, but type-safe and object-oriented. A delegate defines a contract (method signature), and any method matching that signature can be assigned to it.
Delegates are widely used for:
- Events and callbacks
- Implementing the Observer pattern
- Writing extensible and flexible code
Declaring and Using a Delegate
Basic syntax:
// 1. Declare a delegate
delegate void MyDelegate(string message);
// 2. Define methods with the same signature
void ShowMessage(string msg)
{
Console.WriteLine("Message: " + msg);
}
void ShowUpper(string msg)
{
Console.WriteLine("Upper: " + msg.ToUpper());
}
// 3. Use delegate
MyDelegate d1 = ShowMessage;
d1("Hello C#!");
MyDelegate d2 = ShowUpper;
d2("Hello world");
👉 In this example:
delegate void MyDelegate(string message)defines a delegate withvoidreturn type and onestringparameter.- Both
ShowMessageandShowUppermatch the signature, so they can be assigned toMyDelegate.
Multicast Delegate
A delegate in C# can hold references to multiple methods at once. When invoked, it calls all of them in order.
Example:
delegate void Notify(string msg);
class Program
{
static void ShowInfo(string msg) => Console.WriteLine("Info: " + msg);
static void ShowWarning(string msg) => Console.WriteLine("Warning: " + msg);
static void Main()
{
Notify notify = ShowInfo;
notify += ShowWarning; // Add another method
notify("This is a notification!");
}
}
Output:
Info: This is a notification! Warning: This is a notification!
Delegate with Lambda Expressions
Instead of writing separate methods, you can use lambda expressions to keep things short and clean:
delegate int Calculator(int a, int b);
class Program
{
static void Main()
{
Calculator add = (x, y) => x + y;
Calculator multiply = (x, y) => x * y;
Console.WriteLine("Sum: " + add(5, 3)); // 8
Console.WriteLine("Product: " + multiply(5, 3)); // 15
}
}
Conclusion
- A delegate is a powerful feature in C# that allows methods to be treated as objects.
- They are essential for event-driven programming, callbacks, and Observer pattern implementations.
- Combined with lambda expressions and LINQ, delegates make C# code more readable, flexible, and maintainable.
