C# – Event Subscription from Nested Classes

cnet

Is it OK to have a nested class raise an event and for the parent class that subscribes to that event subsequently raise another event, which it's parent class has subscribed to – thus passing the original event up the class hierarchy?

It may be easy to explain like this…

We have…

Class A
Class B
Class C

Operation…

  1. Class C raises an event
  2. Class B subscribes to that event, on notification it raises another event
  3. Class A subscribes to Class B event, on notification it does something

So the original event occurred in Class C and Class A is dealing with it.

Using this method means I require event handlers in the middle class (Class B) whose only function is to pass along the notification – this seems a little smelly to me.

Best Answer

Yes, it is OK and it is a good way of hiding the details of your inner events as well as having one class to connect your event listeners to, instead of several one. It does not mean that having multiple events in multiple classes is bad - far from it - just that it helps in increasing the comprehension of your code if all events related to a particular business domain are in the same "place", although the real inner work is done in "child" classes.

There even is a name for it: event bubbling. You may be interested in reading the MSDN article on that subject.