C# – How to write a custom EventHandler class

cevent

When I started using Java, I created a custom Event class to mimic C#'s implementation of Events. Since then, I've added some other features, like event listener priorities, and cascading events were priorities are respected. Now that I'm using C# again, I wanted to create an eventhandler class, or at least a class that I can use the event keyword with, that incorporated these features. Starting off with, I've hit a bit of a brick wall where I can't subclass EventHandler, being told that it's a sealed class, and I can only use the event keyword with EventHandler/EventHandler and its subclasses.

Is this a fool's errand? And should I just lump for a more straight-forward translation of my event class, ignoring the event system already in-place? Or is there I way I can do this successfully?

Best Answer

Just leave out the event keyword, instead of

public event SampleEventHandler SampleEvent;

use just standard delegates (in C#, delegates are multicast enabled). Declare it like this:

delegate void SampleEventHandler(object sender, MyEventArgs e);

Now, for introducing priorities, use something like a priority queue. As a simple form, you can utilize a dictionary:

Dictionary<int,SampleEventHandler> EventDictionary;

where the dictionary keys are the different priorities. This dictionary serves as an "event" in the class where you define it. To add some new event handler, you need something like this:

public void AddNewEvent(int priority,SampleEventHandler handler)
{
     if(!EventDictionary.ContainsKey(priority))
         EventDictionary.Add(priority, null );
     EventDictionary[priority]+=handler;
}

To raise the events in low-prio-first order, you need some code like this:

foreach(int priority in EventDictionary.Keys.OrderBy(p=>p))
     EventDictionary[priority](this,myEventArgs);