Events & Delegates in C#
In C#, delegate helps you set up and run callbacks. It’s like a middleman for one or more function pointers. In the .NET world, we use delegates to handle the concept of function pointers. To put it simply, a delegate acts as a messenger or a pointer to a function. Meanwhile, events are a special kind of delegate that tells you when something specific happens.
How it works
Let’s imagine we’re building a basic notification service in C#. We have a class called Publisher that sends notifications and another class called Subscriber that wants to know when a new message arrives.
1. Define a delegate for notification with custom event arguments. This delegate represents the method signature that the event will call.
public delegate void EventHandler(object obj, NotificationEventArgs args);
2. Create NotificationEventArgs class by extending it from EventArgs.
public class NotificationEventArgs : EventArgs
{
public string Message { get; set; }
public NotificationEventArgs(string message) => Message = message;
}
3. Create a Publisher class that has an event Notify of type EventHandler, which represents the notification event.
public class Publisher
{
public event EventHandler Notify;
public void SendNotification(string message) => Notify?.Invoke(this, new NotificationEventArgs(message));
}
4. Create a Subcriber class with a method RecieveNotification. It will be called when a notification is received.
public class Subscriber
{
public void RecieveNotification(string message) => Console.WriteLine($"Received Notification: {message}");
}
5. In the Main method, instantiate both the Publisher and Subscriber classes. Then, subscribe the Subscriber’s method to the Publisher’s event. At this point, the Subscriber’s ReceiveNotification method is set up to listen to notifications from the Publisher. Now, when we send a notification using SendNotification, it triggers the Notify event, causing the ReceiveNotification method in the Subscriber to run.
class Program
{
public static void Main()
{
Publisher publisher= new Publisher();
Subscriber subscriber = new Subscriber();
publisher.Notify += subscriber.ReceiveNotification;
publisher.SendNotification("Hello, sending a notification!");
}
}