๐ C# Delegates โ Type-Safe Function Pointers for Flexible Code Execution
๐งฒ Introduction โ Why Use Delegates in C#?
In modern C# applications, especially those requiring callbacks, event-driven logic, or functional programming techniques, you often need to treat methods as data. Delegates make this possible by acting as type-safe function pointersโallowing you to pass methods around just like variables.
๐ฏ In this guide, youโll learn:
- What a delegate is and why itโs useful
- How to declare, instantiate, and invoke delegates
- The difference between single-cast and multicast delegates
- Real-world applications like callbacks and events
๐ Core Concept โ What Is a Delegate?
A delegate in C# is a type-safe object that refers to a method with a specific signature and return type. Delegates allow methods to be passed as arguments, stored in variables, or invoked dynamically.
๐ฃ Delegate Declaration Syntax
delegate void Greet(string name);
๐ This defines a delegate named Greet
that can point to any method that takes a string
and returns void
.
๐ป Code Example โ Declaring and Using a Delegate
delegate void Greet(string name);
class Program
{
static void SayHello(string name)
{
Console.WriteLine($"Hello, {name}!");
}
static void Main()
{
Greet greeter = SayHello;
greeter("Alice");
}
}
๐ฅ Output:
Hello, Alice!
๐งต Explanation:
SayHello
matches theGreet
delegate signature.greeter("Alice")
invokes the method indirectly.
๐ Multicast Delegates
A multicast delegate points to multiple methods and invokes them in order.
delegate void Notify();
void Email() => Console.WriteLine("Email sent");
void SMS() => Console.WriteLine("SMS sent");
Notify notify = Email;
notify += SMS;
notify();
๐ฅ Output:
Email sent
SMS sent
๐ Use Case: Trigger multiple listeners, such as event handlers.
๐ Delegates as Parameters
delegate int Operation(int x, int y);
int Add(int a, int b) => a + b;
int Calculate(Operation op, int x, int y) => op(x, y);
int result = Calculate(Add, 5, 3); // Output: 8
๐ Use Case: Pass different operations into a reusable method.
๐ Built-in Delegates
Delegate Type | Signature |
---|---|
Action | No return value (void ) |
Func | Returns a value |
Predicate | Returns a bool |
Example โ Using Action
, Func
, and Predicate
Action<string> print = Console.WriteLine;
Func<int, int, int> add = (a, b) => a + b;
Predicate<int> isEven = x => x % 2 == 0;
๐ก Best Practices & Tips
๐ก Tip: Use delegates when you want methods as first-class citizens.
โ ๏ธ Pitfall: Multicast delegates only return the last method’s return valueโnot suitable when return values are needed from all calls.
๐ Best Practice: Prefer built-in delegates (Action
, Func
, Predicate
) when possible for clarity and reuse.
๐ ๏ธ Real-World Use Cases
- ๐ฆ Callbacks in async programming
- ๐งช Filtering and transformation in LINQ
- ๐ฎ Game engine events (e.g.,
OnPlayerDeath
) - ๐งฐ Plug-in systems and dynamic method execution
- ๐ Form validation pipelines
๐ Summary โ Recap & Next Steps
๐งต Key Takeaways:
- Delegates enable method references and flexible code execution.
- Support single-cast and multicast patterns.
- Built-in types like
Action
,Func
, andPredicate
simplify common patterns.
โ๏ธ Real-world relevance: Delegates power events, callbacks, LINQ, and functional programming patterns in C#.
โ FAQ Section
โ What is the difference between a delegate and an event?
โ
A delegate is a type-safe method pointer, while an event is a wrapper around a delegate designed for publish/subscribe patterns.
โ Can a delegate point to multiple methods?
โ
Yes. A multicast delegate can reference multiple methods using the +=
syntax.
โ Are delegates reference types or value types?
โ
Delegates are reference types, even though they often wrap method logic.
โ Can I pass a lambda expression to a delegate?
โ
Yes. Lambda expressions are fully compatible with delegate types.
โ Is it better to use delegate
or Action
/Func
?
โ
For simple cases, prefer built-in delegates (Action
, Func
) to reduce boilerplate and improve readability.
Share Now :