C# Events and Delegates in real-time example

Pavan EduPavan Edu
2 min read

Let’s take an example of a notification system for a course purchase.

To effectively use events for notifying course purchases in C#, you can follow a structured approach that leverages the event-driven programming paradigm. This involves defining events, subscribing to them, and ensuring proper handling of notifications.

Below is a detailed guide on how to implement this in your application.

Step-by-Step Implementation

1. Define a Delegate and Event

First, create a delegate that specifies the method signature for the notification handlers. Then, declare an event using this delegate in your class.

public delegate void CoursePurchasedEventHandler(string message);

public class CoursePublisher
{
    public event CoursePurchasedEventHandler CoursePurchased;

    protected virtual void OnCoursePurchased(string message)
    {
        CoursePurchased?.Invoke(message);
    }
}

2. Raise the Event

Within your CoursePublisher class, define a method that triggers the event when a course purchase occurs. This method will call OnCoursePurchased, which notifies all subscribed handlers.

public void PurchaseCourse(string courseName)
{   // Logic for purchasing the course
    Console.WriteLine($"Course '{courseName}' has been purchased.");

    OnCoursePurchased($"The course '{courseName}' has been successfully purchased.");
}

3. Create the Subscriber Class

Next, create a subscriber class that will handle the notifications. This class must implement a method that matches the delegate's signature.

public class CourseSubscriber
{
    public void OnCoursePurchased(string message)
    {
        Console.WriteLine($"Notification received: {message}");
    }
}

4. Subscribe to the Event

In your main program or wherever you manage your application flow, instantiate both the publisher and subscriber classes. Then, subscribe the subscriber's method to the publisher's event.

class Program
{
    static void Main(string[] args)
    {
        CoursePublisher publisher = new CoursePublisher();
        CourseSubscriber subscriber = new CourseSubscriber();

        // Subscribe to the event
        publisher.CoursePurchased += subscriber.OnCoursePurchased;

        // Trigger the purchase
        publisher.PurchaseCourse("C# for Beginners");

        // Unsubscribe when no longer needed
        publisher.CoursePurchased -= subscriber.OnCoursePurchased;
    }
}

5. Best Practices

  • Unsubscribe from Events: Always unsubscribe from events when they are no longer needed to prevent memory leaks.

  • Use Generic EventHandler: Prefer using EventHandler<T> for standard .NET events, which simplifies event handling and reduces boilerplate code.

  • Exception Handling: Implement exception handling in your event handlers to manage potential errors during notification processing.

  • Loose Coupling: Ensure that your publisher does not need to know details about its subscribers, promoting a decoupled architecture.

By following these steps and best practices, you can create an effective notification system for course purchases in C#. This approach enhances modularity and responsiveness within your application.

0
Subscribe to my newsletter

Read articles from Pavan Edu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pavan Edu
Pavan Edu