Event vs Delegate in C#: Key Differences and Usage
delegate is a type that holds references to methods with a specific signature, allowing direct method calls. An event is a special delegate wrapper that restricts direct invocation and is used to provide safe, controlled notifications to subscribers.Quick Comparison
Here is a quick side-by-side comparison of delegate and event in C#.
| Aspect | Delegate | Event |
|---|---|---|
| Definition | Type that holds method references | Wrapper around delegate for safe notifications |
| Invocation | Can be invoked directly | Can only be invoked within declaring class |
| Access Control | No built-in restrictions | Restricts external invocation |
| Usage | Used for callback methods | Used for publish-subscribe pattern |
| Subscription | Methods added/removed like delegate | Methods added/removed via += and -= only |
| Encapsulation | Less encapsulated | More encapsulated and safer |
Key Differences
A delegate in C# is essentially a type-safe function pointer. It can hold references to one or more methods matching its signature and can be invoked directly by any code that has access to it. This makes delegates flexible but also means any code with access can call the delegate, which might lead to unintended behavior.
An event is built on top of delegates to provide a controlled way to notify multiple subscribers. It restricts who can invoke the delegate, usually only allowing the class that declares the event to raise it. External code can only subscribe or unsubscribe using += or -=, but cannot invoke the event directly. This encapsulation helps prevent accidental or malicious invocation.
In summary, use delegate when you need a simple method reference or callback, and use event when you want to implement a publish-subscribe pattern with controlled access to the invocation.
Code Comparison
This example shows how to use a delegate to hold and invoke methods directly.
using System; public delegate void Notify(string message); class Program { static void Main() { Notify notify = ShowMessage; notify("Hello from delegate!"); } static void ShowMessage(string msg) { Console.WriteLine(msg); } }
Event Equivalent
This example shows how to use an event to allow subscription and controlled invocation.
using System; class Publisher { public event Action<string> Notify; public void RaiseEvent(string message) { Notify?.Invoke(message); } } class Program { static void Main() { Publisher pub = new Publisher(); pub.Notify += ShowMessage; pub.RaiseEvent("Hello from event!"); } static void ShowMessage(string msg) { Console.WriteLine(msg); } }
When to Use Which
Choose delegate when: you need a simple, direct reference to one or more methods and want to invoke them yourself without restrictions.
Choose event when: you want to implement a notification system where multiple subscribers can listen but only the declaring class can raise the notifications, ensuring safer and more controlled code.