I want to add events to some built in .NET classes. For example I want to add the following events to a generic List(T):
- ItemAdded
- ItemRemoved
- ListChanged
- etc
I can think of a few ways to accomplish this, but I’m not sure which approach is best.
- I could use “extension events“, that is, if there is such a thing or a way to use extension methods to simulate event-like functionality.
- I could inherit from
List(T)and override the necessary methods and properties. - I could inherit from
List(T)and shadow the necessary methods and properties. - I could create a new class that implements
IList(T)and then wrap the remaining functionality ofList(T)thatIList(T)is missing.
Obviously option 4 is the most work, which is not a big deal if I only wanted to extend one class. However, I also want to avoid nasty side effects.
What are the advantages, disadvantages, and caveats for each approach?
Note: I’m not really concerned here with IList(T) specifically. I find myself wanting to add “extenstion events” to other classes as well.
There’s no such thing as “extension events” and you can’t use extension methods to simulate this: extension events can’t add state to existing classes, which is what you’d require.
I think you mean override rather than overload. This will work, this it’s slightly clumsy – and means you couldn’t use the normal
ToListfrom LINQ etc, because then you’d just get aList<T>.Shadowing is nastier than overriding. It means that the events may or may not be raised based on how the caller is calling the method. Ick.
This would be preferable, and you could add an extension method to
List<T>to wrap it. One disadvantage is that if anyone else “knows about” the unwrapped collection, you won’t spot changes made that way.Have you looked at
ObservableCollection<T>? Note that this will copy from a list if you provide it in the constructor, rather than wrapping the list.