Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Events vs Delegates in C#
In C#, both delegates and events provide mechanisms for method invocation, but they serve different purposes and have distinct characteristics. Events are built on top of delegates but provide additional safety and encapsulation features that make them more suitable for notification scenarios.
Syntax
Following is the syntax for declaring a delegate −
public delegate void DelegateName(parameters);
Following is the syntax for declaring an event −
public delegate void DelegateName(parameters); public event DelegateName EventName;
Delegates in C#
A delegate is a reference type that holds references to methods with the same signature. Delegates can be assigned directly using the assignment operator and can hold multiple method references through multicast delegation.
Example
using System;
public delegate void PrintDelegate(string message);
class Program {
public static void Method1(string msg) {
Console.WriteLine("Method1: " + msg);
}
public static void Method2(string msg) {
Console.WriteLine("Method2: " + msg);
}
public static void Main() {
PrintDelegate del = Method1;
del += Method2;
Console.WriteLine("Calling delegate:");
del("Hello World");
// Direct assignment overwrites existing methods
del = Method2;
Console.WriteLine("\nAfter direct assignment:");
del("Only Method2");
}
}
The output of the above code is −
Calling delegate: Method1: Hello World Method2: Hello World After direct assignment: Method2: Only Method2
Events in C#
An event is a special kind of multicast delegate that provides additional restrictions and safety. Events prevent external classes from directly assigning or invoking the event, allowing only subscription and unsubscription through += and -= operators.
Example
using System;
public delegate void NotifyDelegate(string message);
class Publisher {
public event NotifyDelegate OnNotify;
public void TriggerEvent(string msg) {
OnNotify?.Invoke(msg);
}
}
class Subscriber {
public void HandleNotification(string msg) {
Console.WriteLine("Subscriber received: " + msg);
}
}
class Program {
public static void Main() {
Publisher pub = new Publisher();
Subscriber sub = new Subscriber();
// Subscribe to event
pub.OnNotify += sub.HandleNotification;
pub.OnNotify += (msg) => Console.WriteLine("Lambda handler: " + msg);
Console.WriteLine("Triggering event:");
pub.TriggerEvent("Event fired!");
// Unsubscribe
pub.OnNotify -= sub.HandleNotification;
Console.WriteLine("\nAfter unsubscribing first handler:");
pub.TriggerEvent("Second event!");
}
}
The output of the above code is −
Triggering event: Subscriber received: Event fired! Lambda handler: Event fired! After unsubscribing first handler: Lambda handler: Second event!
Key Differences
| Aspect | Delegate | Event |
|---|---|---|
| Access Level | Can be assigned, invoked, and modified directly | Only += and -= operators allowed externally |
| Assignment | del = method (overwrites existing) | evt = method (compile-time error) |
| Invocation | del() allowed from anywhere | Only the declaring class can invoke |
| Safety | Can be accidentally overwritten | Protected from external modification |
| Use Case | Callbacks, functional programming | Notifications, observer pattern |
When to Use Each
Use delegates when you need a function pointer for callbacks or when external code needs full control over the method reference. Use events when implementing the observer pattern or when you need to notify multiple subscribers while maintaining encapsulation and preventing external interference.
Conclusion
Events provide a safer, more encapsulated way to implement notifications compared to delegates. While delegates offer flexibility and direct access, events prevent accidental overwrites and unauthorized invocations, making them ideal for publisher-subscriber scenarios where multiple components need to respond to state changes.
