views:

84

answers:

2

I have a class which has a member object (class variable). This object has some events. I'd like to expose these events directly in my class. What is the best way to do this?

+1  A: 

If you want to expose the events directly (without defining new handlers that you would forward to your subscribers) you could do this:

class MyClass {

    private readonly OtherClass other = new OtherClass();

    public event EventHandler Click {
     add { other.Click += value; }
     remove { other.Click -= value; }
    }

}

The advantage to this method is that you don't need to handle the events from OtherClass and forward them as your own. The disadvantage (and the reason I declared the "other" field as readonly) is that anyone who hooks up to MyClass's Click event is really hooking up to OtherClass's Click event indirectly. So you wouldn't want to just change out the other instance because subscribers that were already handling the event wouldn't be called.

Josh Einstein
In particular, note that event handlers will receive reference to inner object as `sender` argument. If you intentionally do not otherwise expose the inner object, it may be an encapsulation breaker.
Pavel Minaev
A: 

Check out this question...

Rohan West