Definition |
A delegate is a type that defines a method signature. |
An event is a higher-level abstraction built on top of delegates. |
Usage |
Primarily used to define and reference methods that can be invoked later. |
Used for implementing the observer or publisher-subscriber pattern, allowing classes to subscribe to and respond to notifications. |
Multicast |
Supports multicast; can hold references to multiple methods. |
Uses delegates internally but typically exposes only the `add` and `remove` accessors to control subscription and unsubscription. |
Event Handling Semantics |
Delegates do not provide event handling semantics. |
Events provide clear semantics for subscription and unsubscription. Subscribers use `+=` to subscribe and `-=` to unsubscribe. |
Direct Invocation |
Methods referenced by delegates can be invoked directly using the delegate object. |
Event handlers cannot be directly invoked from outside the class that defines the event. They are only invoked by the class that raises the event. |
Example |
public delegate void MyDelegate(string message);
MyDelegate myDelegate = SomeMethod;
myDelegate += AnotherMethod;
myDelegate("Hello");
|
public class Publisher
{
public event EventHandler MyEvent;
public void RaiseEvent()
{
MyEvent?.Invoke(this, EventArgs.Empty);
}
}
public class Subscriber
{
public void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine("Event handled by Subscriber");
}
}
// Usage:
var publisher = new Publisher();
var subscriber = new Subscriber();
publisher.MyEvent += subscriber.HandleEvent;
publisher.RaiseEvent(); // Subscriber's HandleEvent method is called
|