I was going to post about how I wrote the must terrible C# event routing code ever at work Thursday afternoon.
I defined an interface
INewContent, which has a single member "
event NewContentHandler NewContent".
By implementing this interface, a class signals that it will be providing new content that it wants some control up the chain to process. There are only two ways to process content: display it or pass it on up the chain.
Now, the
.NET class library guidelines say to (and the .NET framework does) implement a
protected virtual method "
OnMyEvenet(MyEventArgs e)" for every public event with signature "
MyEventHandler(object sender, MyEventArgs e)".
The deal is, subclasses can override this method to do special case event raising. This is sometimes better than a class listening to its own events, as you can gaurantee the order in which your handling happens in relation to any other objects that have hooked the event.
Now, all the classes I have that implement
INewContent had an
OnNewContent, usually defined in a common base class. In most cases, I want an object that is listening to other objects'
NewContent events to reraise the event as their own
NewContent event.
The problem is, the event signature has an "
object sender" parameter, but the event raising method doesn't (almost always, the event raising method sets itself as the sender.)
So I came up with some rigamarole in a static utility class to translate between the two kinds of methods.
Then the next morning I realized that I had been a slave to orthodoxy.
I took out
OnNewContent(MyEventArgs e) from the base class and replaced it with
HandleNewContent(object sender, MyEventArgs e).
Now when an object A listens to content from object B, it hooks the object B's
NewContent event to its own
HandleNewContent, which by default just reraises the event for whoever is listening to object A.
Still wonky, but much less so than having a separate static class that does event routing.
The moral of the story is, know when to ignore the guidelines.