Example of Event in C# - Delegate with the custom EventArgs

Rumman Ansari   Software Engineer   2024-07-12 09:14:29   474  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Step-by-Step

  1. Define a custom EventArgs class:

    In this context, NewIssueEventArgs is a derived class of EventArgs. This means that NewIssueEventArgs inherits from EventArgs, making it a specialized version of EventArgs with additional properties specific to the new issue event (e.g., IssueNumber and IssueTitle).

    Here's a breakdown:

    • Base Class: EventArgs is a predefined class in the .NET framework used as the base class for classes containing event data.
    • Derived Class: NewIssueEventArgs inherits from EventArgs and adds additional properties (IssueNumber and IssueTitle).
  2. 
    public class NewIssueEventArgs : EventArgs
    {
        public int IssueNumber { get; }
        public string IssueTitle { get; }
    
        public NewIssueEventArgs(int issueNumber, string issueTitle)
        {
            IssueNumber = issueNumber;
            IssueTitle = issueTitle;
        }
    }
    
    
  3. The event to use the custom EventArgs class:

  4. 
    public class MagazineCompany
    {
        // Define a delegate with the custom EventArgs
        public delegate void NewIssueEventHandler(object sender, NewIssueEventArgs e);
    
        // Define an event based on the delegate
        public event NewIssueEventHandler NewIssue;
    
        // Method to raise the event with custom event data
        public void PublishNewIssue(int issueNumber, string issueTitle)
        {
            Console.WriteLine("Magazine Company: Publishing new issue...");
            OnNewIssue(new NewIssueEventArgs(issueNumber, issueTitle));
        }
    
        // Protected virtual method to allow derived classes to override the event invocation behavior
        protected virtual void OnNewIssue(NewIssueEventArgs e)
        {
            // Invoke the event handler, if there are any subscribers
            NewIssue?.Invoke(this, e);
        }
    }
    
    
  5. The event handler to use the custom EventArgs class:
  6. 
    public class Reader
    {
        // Method that will be called when the event is raised
        public void OnNewIssueReceived(object sender, NewIssueEventArgs e)
        {
            Console.WriteLine($"Reader: Received new issue {e.IssueNumber} titled '{e.IssueTitle}'.");
        }
    }
    
    
  7. Example usage:
  8. 
    public class Program
    {
        public static void Main(string[] args)
        {
            // Create a magazine company (Publisher)
            MagazineCompany magazineCompany = new MagazineCompany();
            
            // Create a reader (Subscriber)
            Reader reader = new Reader();
            
            // Subscribe the reader to the magazine company's new issue event
            magazineCompany.NewIssue += reader.OnNewIssueReceived;
            
            // Publish a new issue with additional event data
            magazineCompany.PublishNewIssue(42, "The Future of Technology");
        }
    }
    
    

Explanation

  • Custom EventArgs Class: NewIssueEventArgs contains properties for the issue number and title.
  • Delegate and Event: NewIssueEventHandler uses the custom EventArgs.
  • Raising the Event: OnNewIssue method raises the event, passing an instance of NewIssueEventArgs with the issue number and title.
  • Event Handler: OnNewIssueReceived method of Reader class handles the event and can access the additional data (issue number and title).

When you run the program, the output will be:


Magazine Company: Publishing new issue...
Reader: Received new issue 42 titled 'The Future of Technology'.



Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.