Custom Events in C# for Enhanced Communication and Flexibility

Introduction

In C#, custom events offer a means for classes to interact and respond to specific actions or changes in state. Built upon delegates, they frequently implement the observer pattern, facilitating the publisher-subscriber model.

Below is a guide illustrating how to define and employ custom events in C#.

Step 1. Define an event

Events can be defined in two ways: either utilizing an Action delegate or through an EventHandler. If the user intends to pass parameters via event arguments, they must define an event argument class that inherits from EventArgs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfAppActionDelegate
{
    internal class EventManager
    {
        public static event EventHandler<CustomEventArgs> CustomHandlerEvent;//EventHandler
        public static event Action<object, CustomEventArgs> CustomEvent;//Action Delegate

        public void RaiseCustomEvent(EventArgsModel model)
        {
            CustomEventArgs customEventArgs = new CustomEventArgs();
            customEventArgs.Message =model.Message;
            customEventArgs.lstStr = model.lstStr;
            CustomEvent?.Invoke(this, customEventArgs);
        }

        public void Raise_CustomHandlerEvent(EventArgsModel model)
        {
            CustomEventArgs customEventArgs = new CustomEventArgs();
            customEventArgs.Message = model.Message;
            customEventArgs.lstStr = model.lstStr;
            CustomHandlerEvent?.Invoke(this, customEventArgs);
        }
    }
    public class CustomEventArgs : EventArgs
    {
        public string Message { get; set; }
        public List<string> lstStr { get; set; }
    }
}

Define a model class to be utilized for passing parameters in the form of event arguments.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfAppActionDelegate
{
    internal class EventArgsModel
    {
        public string Message { get; set; }
        public List<string> lstStr { get; set; }
    }
}

Step 2. Publish an event

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfAppActionDelegate
{
    internal class PublishEvent
    {
        List<string> lstString=new List<string>();
        public PublishEvent() {
            lstString.Add("Lst1");
            lstString.Add("Lst2");
            lstString.Add("Lst3");

            EventManager eventManager = new EventManager();
            EventArgsModel model = new EventArgsModel();

            model.Message = "Demo Event Publish value";
            model.lstStr = lstString;

            eventManager.RaiseCustomEvent(model);
            eventManager.Raise_CustomHandlerEvent(model);
        }
    }
}

Step 3. Subscribe to an event

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfAppActionDelegate
{
    internal class EvenSubscriber1
    {
        public EvenSubscriber1()
        {
            //EventManager.CustomEvent += EventManager_CustomEvent1;
            EventManager.CustomEvent += CustomEventSubcriber.SubscribeEvent;
            EventManager.CustomHandlerEvent += EventManager_CustomHandlerEvent;
        }

        private void EventManager_CustomHandlerEvent(object? sender, CustomEventArgs e)
        {
            MessageBox.Show("Event subscriber by EventHandler 1 " + e.Message);
        }

        private void EventManager_CustomEvent1(object arg1, CustomEventArgs arg2)
        {
            MessageBox.Show("Event subscriber "+arg2.Message);
        }

        private void EventManager_CustomEvent()
        {
         
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfAppActionDelegate
{
    internal class EvenSubscriber2
    {
        public EvenSubscriber2()
        {
            EventManager.CustomEvent += EventManager_CustomEvent1;
            EventManager.CustomHandlerEvent += EventManager_CustomHandlerEvent;
        }

        private void EventManager_CustomHandlerEvent(object? sender, CustomEventArgs e)
        {
            MessageBox.Show("Event subscriber by EventHandler 2" + e.Message);
        }

        private void EventManager_CustomEvent1(object arg1, CustomEventArgs arg2)
        {
            MessageBox.Show("Event subscriber "+arg2.Message);
        }

        private void EventManager_CustomEvent()
        {
            MessageBox.Show("Event subscriber 2");
        }
    }
}

To utilize a custom method, we need to define a class as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfAppActionDelegate
{
    internal class CustomEventSubcriber
    {
        public static void SubscribeEvent(object arg1, CustomEventArgs arg2)
        {
            MessageBox.Show("Event raised by custom class method "+arg2.Message);
        }
    }
}

Step 4. To invoke a publish and subscribe event

To invoke a publish and subscribe event.

using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfAppActionDelegate
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            EvenSubscriber1 subscriber1 = new EvenSubscriber1();
            EvenSubscriber2 subscriber2 = new EvenSubscriber2();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
           // MessageBox.Show("Demo");
           PublishEvent publishEvent = new PublishEvent();
        }
    }
}

Repository path: https://github.com/OmatrixTech/CustomEventExample


Similar Articles