ALLINSIGHT

Home of the AlmostImplementedException

Introducing Events

Sometimes we have to know what happens inside other objects like a collection where new entries are added or removed. So we have to make use of a nice feature called Events.
In this post I will give you a first insight in Events with a snippet for an observable collection called WatchedList. Observable collections are part of the .Net Framework since version 3.0.
At the time i needed the observable collection I worked with version 2.0 of the framework. So please excuse my bad coding convention. But for demonstrating user defined event I think this is a good practise.
So what are Events? Events are notificators for objects where something “interesting” happens so other objects can react. In fact this means: Object A was changed and fires an event. Object B has subscribed to this event at Object A and is now notified that something happens. The design pattern for .net recommends that you have an object sender and event arguments e.
The eventhandler should look like this for our WatchedList:

We define a delegate to define how the subscribed event catcher looks and call this ChangedEventHandler.
At next we will define the event itself with the public name as type of ChangedEventHandler:

Last but not least we have to define a method that is called inside the class to specify that the event should be fired.

Now we have the basic construct for events. The ListEventArgs object is a custom class for providing the needed informations whenn the list is changed.
This class makes need of the enum ListChangedType to indicate how the list was changed.

Now we have all to implement our observable collection. At first we create a System.Collections.Generic.List derived class called WatchedList and implement the three members for event handling mentioned before. For the functionality of notification when the list changed we need to override the derived methods that make changes at the list, like Add, Remove and call the base-method inside before we call the method OnChanged with a new object of ListEventArgs. When this all is done our WatchedList should look like this (complete with ListEventArgs and ListChangedType):

Share :

,

Comments are currently closed.