views:

132

answers:

5

I need a .net Collection that has Add and Remove events. Is there a premade version that has that?

For example, I would update some internal counter when a user adds an item to the list via the event. (Not really what I plan to do.)

+10  A: 

Try ObservableCollection<T> it supports INotifyCollectionChanged which supplies events for every aspect of collection modification.

Namespace: System.Collections.ObjectModel

Assembly: WindowsBase.dll

Aviad P.
It's moving into system.dll in 4.0, btw
Will
For .NET 2 there is also BindingList<T> (http://msdn.microsoft.com/en-us/library/ms132679.aspx) which unfortunately doesn't have that fine-grained event support.
Joey
I actually ended up going with the BindingList<T>. ObservableCollection<T> does not support Compact Framework so I could not use that (my bad for not mentioning that). Thanks both for the answers. (Johannes, I voted up 30pts on some of your answers to "pay" for your comment.) Thanks again!
Vaccano
+5  A: 

ObservableCollection<T> is as close as you'll get in the framework.

OTOH, it isn't that hard to do this. Just create a class that implements IList and wraps an internal List<T> instance. You can just throw your events as needed.

Will
A: 

You can also write a custom lightweight wrapper if you wish to optimize for speed at the expense of flexibility.

Hamish Grubijan
A: 

Not that i know of but this would be pretty easy to implement, you can just create your own add and remove methods, or you could use an indexer. Then you can do whatever you like in terms of events.

Paul Creasey
+1  A: 

You could always make a private List<...> and then access through a method:

private List<string> listOfStrings = new List<string>;

public void AddToList(string s)
{
    // Do your work
    listOfStrings.Add(s);
}

or you could overload it and add events however you wish.

md5sum