*
📣 Delegates in C#
A delegate is a type-safe reference to a method. It allows methods to be passed as parameters, stored, and invoked dynamically. Delegates are foundational for events, callbacks, and functional programming in C#.
🧩 Types of Delegates
- Single-cast Delegate: Points to one method at a time.
- Multicast Delegate: Points to multiple methods and invokes them in order.
- Generic Delegate: Uses built-in types like
Action, Func, and Predicate.
📘 Example: Custom Delegate
public delegate void GreetDelegate(string name);
public static void SayHello(string name) {
Console.WriteLine("Hello, " + name);
}
GreetDelegate greet = SayHello;
greet("Shivshanker");
🔁 Multicast Delegate Example
public delegate void Notify();
public static void MethodA() => Console.WriteLine("Method A");
public static void MethodB() => Console.WriteLine("Method B");
Notify notify = MethodA;
notify += MethodB;
notify(); // Calls MethodA and MethodB
🔧 Built-in Delegates
- Action<T>: Represents a method that takes parameters and returns
void.
- Func<T>: Represents a method that takes parameters and returns a value.
- Predicate<T>: Represents a method that takes one parameter and returns a
bool.
🧪 Examples of Built-in Delegates
// Action
Action<int, int> printSum = (a, b) => Console.WriteLine(a + b);
printSum(10, 20); // Output: 30
// Func
Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(5, 7)); // Output: 12
// Predicate
Predicate<int> isEven = num => num % 2 == 0;
Console.WriteLine(isEven(4)); // Output: True
✅ Best Practices
- Use built-in delegates for cleaner and more concise code.
- Prefer lambda expressions for inline delegate logic.
- Unsubscribe delegates from events to avoid memory leaks.
- Use multicast delegates carefully—exceptions in one method can affect others.
📌 When to Use
- For event handling in UI or service layers.
- To implement callbacks in asynchronous operations.
- In LINQ queries and functional-style programming.
- To decouple method invocation from method definition.
🚫 When Not to Use
- For simple method calls—direct invocation is clearer.
- In performance-critical code—delegates add slight overhead.
- For long-lived logic—prefer interfaces or strategy patterns.
⚠️ Precautions
- Ensure delegate signature matches the target method exactly.
- Handle exceptions inside delegate-invoked methods.
- Avoid storing delegates in fields unless necessary.
🎯 Advantages
- Flexibility: Methods can be passed and invoked dynamically.
- Encapsulation: Behavior can be abstracted and reused.
- Event support: Delegates are the backbone of .NET events.
- Functional style: Enables cleaner, more expressive code.
📝 Conclusion
Delegates in C# offer a powerful way to work with methods as first-class objects. Whether you're building event-driven systems or writing functional-style code, understanding delegates—and their built-in variants—can make your applications more modular and expressive.
*