- 1. What is an Event?
- 2. How to Declare an Event
- 3. How to Subscribe to an Event
- 4. Output
- 5. Key Points
In C#, an event is a messaging system built on top of delegates that allows one object to notify other objects when something happens. This is often described as the publisher–subscriber model.
1. What is an Event?
- An event is a special kind of delegate.
- It is used when you want to signal a change or an action has occurred (publisher), and you allow other parts of the program (subscribers) to react.
- Example: A
Buttonclick in Windows Forms is an event. When the button is clicked, it triggers theClickevent, and any methods subscribed to it will run.
2. How to Declare an Event
public class Process
{
// Declare a delegate type
public delegate void ProcessCompletedHandler(string message);
// Declare an event based on that delegate
public event ProcessCompletedHandler ProcessCompleted;
public void Start()
{
Console.WriteLine("Process started...");
// Do some work (simulate with sleep)
System.Threading.Thread.Sleep(2000);
// Trigger the event
OnProcessCompleted("Process finished successfully!");
}
// Protected virtual method to raise the event
protected virtual void OnProcessCompleted(string message)
{
// Check if event has subscribers
if (ProcessCompleted != null)
ProcessCompleted(message);
}
}
3. How to Subscribe to an Event
class Program
{
static void Main()
{
Process process = new Process();
// Subscribe to the event
process.ProcessCompleted += ShowMessage;
// Start the process
process.Start();
}
// Event handler (same signature as delegate)
static void ShowMessage(string msg)
{
Console.WriteLine("Event received: " + msg);
}
}
4. Output
Process started... Event received: Process finished successfully!
5. Key Points
- Publisher: The class that defines and raises the event (
Process). - Subscriber: The class that listens and reacts to the event (
Program). - Events ensure encapsulation: subscribers cannot invoke the event directly, only the publisher can.
✅ In real life:
- WinForms/WPF/ASP.NET use events heavily (e.g.,
Button.Click,TextBox.TextChanged). - You can even use the built-in
EventHandlerdelegate instead of creating your own.
