C# Events and Delegates in simple content.
Delegates and events are fundamental concepts in C# that facilitate event-driven programming. They allow methods to be passed as parameters and enable a publisher-subscriber model, where one part of the code (the publisher) can notify other parts (the subscribers) when something happens.
What are Delegates?
Delegates are function pointer in C#. It can only point to functions which are matching to the signature of the delegate. Delegates are very useful to write loosely coupled codes, also it is used to code event-based actions.
In other words, a delegate is a type that represents references to methods with a specific signature. It can be thought of as a type-safe function pointer. Delegates allow methods to be passed as parameters, enabling callback functions and event handling.
Example of a Delegate
Here's a simple example demonstrating how to declare and use a delegate:
using System;
public delegate void Notify(string message); // Declare a delegate
class Program
{
public static void Main(string[] args)
{
Notify notifyDelegate = ShowMessage; // Assign method to delegate
notifyDelegate("Hello from the delegate!"); // Invoke the delegate
}
public static void ShowMessage(string message)
{
Console.WriteLine(message); // Print the message
}
}
In this example:
We declare a delegate
Notify
that takes a string parameter.We create an instance of the delegate and assign it to the method
ShowMessage
.When we invoke the delegate, it calls
ShowMessage
and prints the message.
What are Events?
An event is a special kind of delegate that is used to provide notifications.
Events in C# can be used to notify the occurrence or completion of something that is useful to some other subscribers. The event can be something like completion of a task, button click, etc. Code which raises an event called the publisher. The code that subscribes to get notified is known as the subscriber.
Events are typically used in GUI applications to respond to user actions, such as button clicks. An event can have multiple subscribers, allowing multiple methods to be called when the event is raised.
Delegates and Events in C# related. The event in C# is encapsulated over delegates. Method subscribed to events using the operator “+=” also methods can be unsubscribed using the operator “-=“.
Example of an Event
Here’s an example that combines both delegates and events:
using System;
public delegate void Notify(string message); // Declare a delegate
public class Publisher
{
public event Notify OnNotify; // Declare an event using the delegate
public void RaiseEvent(string message)
{
OnNotify?.Invoke(message); // Raise the event if there are subscribers
}
}
public class Subscriber
{
public void HandleEvent(string message)
{
Console.WriteLine("Received: " + message); // Handle the event
}
}
class Program
{
static void Main(string[] args)
{
Publisher publisher = new Publisher(); // Create publisher instance
Subscriber subscriber = new Subscriber(); // Create subscriber instance
publisher.OnNotify += subscriber.HandleEvent; // Subscribe to the event
publisher.RaiseEvent("Hello World!"); // Raise the event
}
}
In this example:
We define a
Publisher
class with an eventOnNotify
.The
RaiseEvent
method raises this event.The
Subscriber
class has a methodHandleEvent
that handles the notification.In the
Main
method, we create instances of both classes, subscribe to the event, and then raise it.
When you run this code, it will output:
textReceived: Hello World!
This demonstrates how events can be used in C# to create a flexible and decoupled architecture where publishers and subscribers can interact without needing to know about each other's implementations.
Let’s look for one more example (from an external source),
using System;
using System.Collections.Generic;
namespace Learn
{
public delegate void OnCompleteHandler();
public class Publisher
{
public event OnCompleteHandler OnCompleted;
//Publisher operation
public void ProduceMessage(string Message)
{
Console.WriteLine(Message);
//Publisher tells to Notify the completion.
NotifySubscribers(Message);
}
protected virtual void NotifySubscribers(string message)
{
//Notify all the subscribers
OnCompleted?.Invoke();
}
}
public class Subscriber
{
public static void subscriber1()
{
Console.WriteLine("Subscriber 1 called");
}
public static void subscriber2()
{
Console.WriteLine("Subscriber 2 called");
}
}
class Practice
{
public static void Main(string[] args)
{
Publisher publisher = new Publisher();
//subscribe to the event OnCompleted
publisher.OnCompleted += Subscriber.subscriber1;
publisher.OnCompleted += Subscriber.subscriber2;
publisher.ProduceMessage("Hello");
}
}
}
Subscribe to my newsletter
Read articles from Pavan Edu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by