I have a class MyCol, which inherits from ObservableCollection(Of T). It overrides InsertItem method in such manner:
Public Event PreInsertItem As EventHandler(Of EventArgs)
Protected Overridable Sub OnPreInsertItem(e As EventAtgs)
RaiseEvent PreInsertItem(Me, e)
End Sub
Protected Overrides Sub InsertItem(index As Integer, item As T)
OnPreInsertItem(EventArgs.Empty)
MyBase.InsertItem(index, item)
End Sub
As you can see I have added an event which is raised every time an item is added to MyCol collection.
Next I create another class MyColSubClass, which inherits from MyCol, and also overrides InsertItem method:
Public Overrides Sub InsertItem(index as Integer, item as T)
OnPreInsertItem(EventArgs.Empty)
' some additional code goes here
MyBase.InsertItem(index, item)
End Sub
THE QUESTION:
Now, when I use an instance of MyColSubClass and add an item, PreInsertItem event is raised twice: first in MyColSubClass and than in MyCol.
What design pattern should I use to make PreInsertItem event raise only once: in MyColSubClass?
N.B.
Classes and events, shown in examples are simplified from real life application, but assume they show exact structure of application. Raising event in last inherited class is a must.
If you know for sure that the base class will raise the event, it’s useless to do so in the derived class.
Just change your override to :
And that should be fine.
But if you change your derived method, and stop calling MyBase.InsertItem(…), you should raise the event in your override to ensure it gets raised :
EDIT
If you need to change the way the event is raised, but want to make sure that it only gets raised once, simply override the OnPreInsertItem method in your derived class :
Since OnPreInsertItem is overridable, the version from your derived class will get called when you insert an item in your derived class.
Hope that helps 🙂