C# Events and Delegates in real-time example #2

Pavan EduPavan Edu
3 min read

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

To demonstrate the use of delegates and events in an ASP.NET Core application, let's create a simple e-commerce scenario involving course purchases and completions. This example will include delegates for notifying subscribers about the status of a course purchase and completion.

Code Example

Here’s how to set up the classes, delegates, and events in C#:

using System;
namespace ECommerceExample
{
    // Delegate for course status notifications
    public delegate void CourseStatusHandler(object sender, CourseEventArgs e);

    // Event arguments class to hold course information
    public class CourseEventArgs : EventArgs
    {
        public string CourseName { get; set; }
        public string Status { get; set; }

        public CourseEventArgs(string courseName, string status)
        {
            CourseName = courseName;
            Status = status;
        }
    }

    // Publisher class that raises events
    public class Course
    {
        // Event declaration using the delegate
        public event CourseStatusHandler CourseStatusChanged;

        // Method to simulate course purchase
        public void PurchaseCourse(string courseName)
        {
            Console.WriteLine($"Purchasing course: {courseName}");
            //....
            //....
            OnCourseStatusChanged(new CourseEventArgs(courseName, "Purchased"));
        }

        // Method to simulate course completion
        public void CompleteCourse(string courseName)
        {
            Console.WriteLine($"Completing course: {courseName}");
            //....
            //....
            OnCourseStatusChanged(new CourseEventArgs(courseName, "Completed"));
        }

        // Protected virtual method to raise the event
        protected virtual void OnCourseStatusChanged(CourseEventArgs e)
        {
            CourseStatusChanged?.Invoke(this, e);
        }
    }

    // Subscriber class that listens for events
    public class User
    {
        public string Name { get; set; }

        public User(string name)//ctor
        {
            Name = name;
        }

        // Method to handle course status changes
        public void OnCourseStatusChanged(object sender, CourseEventArgs e)
        {
            Console.WriteLine($"{Name} notified: The course '{e.CourseName}' is now '{e.Status}'.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Create instances of the publisher and subscriber
            Course course = new Course();
            User user1 = new User("Alice");
            User user2 = new User("Bob");

            // Subscribe to the event
            course.CourseStatusChanged += user1.OnCourseStatusChanged;
            course.CourseStatusChanged += user2.OnCourseStatusChanged;

            // Simulate purchasing and completing a course
            course.PurchaseCourse("C# Programming");
            course.CompleteCourse("C# Programming");

            Console.ReadKey();
        }
    }
}

Explanation

  1. Delegate Declaration: The CourseStatusHandler delegate is defined to handle events related to the status of a course.

  2. Event Arguments: The CourseEventArgs class inherits from EventArgs and holds information about the course name and its status (purchased or completed).

  3. Publisher Class: The Course class raises events when a course is purchased or completed. It has methods PurchaseCourse and CompleteCourse, which invoke the event through the OnCourseStatusChanged method.

  4. Subscriber Class: The User class subscribes to the events from the Course class. When an event is raised, it handles it through the OnCourseStatusChanged method.

  5. Main Program: In the Main method, instances of Course and User are created. The users subscribe to the CourseStatusChanged event, allowing them to receive notifications when a course is purchased or completed.

Running the Example

When you run this program, it will simulate purchasing and completing a course while notifying all subscribed users about these changes. The output will look like this:

Purchasing course: C# Programming
Alice notified: The course 'C# Programming' is now 'Purchased'.
Bob notified: The course 'C# Programming' is now 'Purchased'.
Completing course: C# Programming
Alice notified: The course 'C# Programming' is now 'Completed'.
Bob notified: The course 'C# Programming' is now 'Completed'.

This example illustrates how delegates and events can be effectively used in an ASP.NET Core application for handling notifications in an e-commerce context.

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