by post@madskristensen.dk (Mads Kristensen) via .NET Slave on 2/3/2007 8:17:11 PM
One of the biggest problems with the different types of collections in the .NET Framework, is that they don’t tell you if the collection as been changed or not. If you have a Collection<int> that has to be persisted to a database, it would be a waste of resources to do so if the collection hasn’t been changed.
That’s why I found it necessary to override the generic Collection<> class to provide it with a property called IsChanged. Everytime you add or remove an item in the collection, the IsChanged property returns true. You can use the property like so:
if (collectionInstance.IsChanged) {//Persist to database }
/// <summary> /// A generic collection with the ability to /// check if it has been changed. /// </summary> [System.Serializable]publicclass StateCollection<T> : System.Collections.ObjectModel.Collection<T> {#region Base overrides/// <summary>/// Inserts an element into the collection at the specified index and marks it changed./// </summary>protectedoverridevoid InsertItem(int index, T item) {base.InsertItem(index, item); _IsChanged =true; }/// <summary>/// Removes all the items in the collection and marks it changed./// </summary>protectedoverridevoid ClearItems() {base.ClearItems(); _IsChanged =true; }/// <summary>/// Removes the element at the specified index and marks the collection changed./// </summary>protectedoverridevoid RemoveItem(int index) {base.RemoveItem(index); _IsChanged =true; }/// <summary>/// Replaces the element at the specified index and marks the collection changed./// </summary>protectedoverridevoid SetItem(int index, T item) {base.SetItem(index, item); _IsChanged =true; }#endregionprivatebool _IsChanged;/// <summary>/// Gets if this object's data has been changed./// </summary>/// <returns>A value indicating if this object's data has been changed.</returns>publicvirtualbool IsChanged { get { return _IsChanged; } set { _IsChanged = value; } } }
Original Post: A state aware generic collection in C#
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.