Forwarding events in C#

For a long time I’ve had a problem with events in C#: I want to wrap one class in another, which offers a higher level of abstraction, but this means that all the events have to be copied and lots of boilerplate code has to be written to do the forwarding. The obvious thing to do would be to have an event exposed as a property, which would give clients of the abstract interface read-only access to the event:

public class HigherLevelClass
{
   public event SomeDelegate MyEvent
   {
      get { return impl.MyEvent; }
   };

   private LowerLevelClass impl;

   /* ... */
}

Unfortunately this isn’t valid syntax, and at first glance that seems to be the end of it. However, I discovered today that the designers of C# have actually thought of this, and provided a way round it:

public class HigherLevelClass
{
   public event SomeDelegate MyEvent
   {
      add { impl.MyEvent += value; }
      remove { impl.MyEvent -= value; }
   };
}

Simple, once you know how. But this illustrates an interesting problem with keyword search when applied to programming techniques: I’ve searched for just this information on several occasions, but wasn’t able to find it until I hit on the magic phrase “event forwarding”. In my experience it’s pretty common to know how to describe what you’d like something to do, but not be able to find the same words as the person who knows how to do it.

I’m sure this is far from the only reason, but perhaps it goes some way to explaining why there are eight separate implementations of every single open source library type, each of which is partially complete.

Leave a Reply

Your email address will not be published. Required fields are marked *