Reputation: 5972
I have a class with properties and collections. It also has a property called Dirty
. I want to set this Dirty
flag if the state of an instance of this class changes in any way.
Obviously for the properties, I can just set this in the setter. However, I'm unsure of the best way of detecting a change in the collection. Whilst I could create my own collection class that derives from the .NET collection class and do it that way, I'm wondering if there's another way which doesn't require my own custom collection type?
Update for clarification
Just to clarify, I don't need to track in a nested way - I literally just want to know if items have been added/removed from the collection.
Upvotes: 2
Views: 2487
Reputation: 10708
See ObservableCollection
which contains the CollectionChanged
event.
Be wary however that ObservableCollection
s are not thread-safe, though there are several tutorials/articles/projects on how to implement such a thing
Upvotes: 2
Reputation: 61349
With your edit, ObservableCollection<T>
would be an excellent choice. It implements INotifyCollectionChanged
, so it will raise an event whenever an item is added or removed.
Note that this class is used all the time in WPF for that exact purpose, so the framework can listen to that event and add/remove UI elements as necessary.
Upvotes: 5