Event forwarding

Written by Dean Edis.

I was having a coding session recently and needed a class to 'pass on' an event fired from a another class.

E.g.
ClassA 'has a' private ClassB. ClassB has an EventB event which occasionally fires.
I want ClassA to have an EventA event which fires whenever EventB does.

My first approach was simple: Have ClassA subscribe to ClassB.EventB. When it receives the event it fires its own EventA.

Did you know...

A simpler approach is to use a custom event subscription:

class ClassA 
{ 
    private ClassB m_b = new ClassB(); 

    public event EventType EventA 
    { 
        add { m_b.EventB += value; } 
        remove { m_b.EventB -= value; } 
    } 
} 

Now, anything subscribing to ClassA.EventA will get its subscription passed on to ClassB, but all without the caller having any direct access to ClassB!

Clean and simple...