0
0
C Sharp (C#)programming~5 mins

Event-driven design pattern in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Event-driven design helps programs respond to actions like clicks or messages. It makes programs wait for events and react when they happen.

When building a user interface that reacts to button clicks or keyboard input.
When you want parts of your program to communicate without being tightly connected.
When handling messages or signals from sensors or external devices.
When you want to run code only after something specific happens, like a file download finishing.
Syntax
C Sharp (C#)
public class Publisher
{
    public event EventHandler? OnChange;

    public void RaiseEvent()
    {
        OnChange?.Invoke(this, EventArgs.Empty);
    }
}

public class Subscriber
{
    public void Subscribe(Publisher pub)
    {
        pub.OnChange += HandleEvent;
    }

    private void HandleEvent(object? sender, EventArgs e)
    {
        Console.WriteLine("Event received!");
    }
}

Events use delegates to connect publishers and subscribers.

The question mark (?) after the event name checks if there are subscribers before calling.

Examples
This line subscribes a method to an event so it runs when the event happens.
C Sharp (C#)
publisher.OnChange += SubscriberMethod;
This line unsubscribes a method so it no longer runs on the event.
C Sharp (C#)
publisher.OnChange -= SubscriberMethod;
This triggers the event safely, only if there are subscribers.
C Sharp (C#)
OnChange?.Invoke(this, EventArgs.Empty);
Sample Program

This program shows a publisher that raises an event and a subscriber that listens and reacts by printing a message.

C Sharp (C#)
using System;

public class Publisher
{
    public event EventHandler? OnChange;

    public void RaiseEvent()
    {
        Console.WriteLine("Publisher: Raising event...");
        OnChange?.Invoke(this, EventArgs.Empty);
    }
}

public class Subscriber
{
    public void Subscribe(Publisher pub)
    {
        pub.OnChange += HandleEvent;
    }

    private void HandleEvent(object? sender, EventArgs e)
    {
        Console.WriteLine("Subscriber: Event received!");
    }
}

public class Program
{
    public static void Main()
    {
        Publisher publisher = new Publisher();
        Subscriber subscriber = new Subscriber();

        subscriber.Subscribe(publisher);

        publisher.RaiseEvent();
    }
}
OutputSuccess
Important Notes

Always unsubscribe from events when no longer needed to avoid memory leaks.

Events help keep code organized by separating who sends and who reacts.

Summary

Event-driven design lets programs react to actions or changes.

Publishers send events; subscribers listen and respond.

This pattern helps build interactive and flexible programs.