A state aware generic collection in C#

Feb 3, 2007

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
}

The code

/// <summary>
/// A generic collection with the ability to
/// check if it has been changed.
/// </summary>
[System.Serializable]
public class 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>
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
_IsChanged = true;
}

/// <summary>
/// Removes all the items in the collection and marks it changed.
/// </summary>
protected override void ClearItems()
{
base.ClearItems();
_IsChanged = true;
}

/// <summary>
/// Removes the element at the specified index and marks the collection changed.
/// </summary>
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_IsChanged = true;
}

/// <summary>
/// Replaces the element at the specified index and marks the collection changed.
/// </summary>
protected override void SetItem(int index, T item)
{
base.SetItem(index, item);
_IsChanged = true;
}

#endregion

private bool _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>
public virtual bool IsChanged
{
get { return _IsChanged; }
set { _IsChanged = value; }
}

}

* $4.95/month ASP.NET Hosting with FREE SQL 2012 DB! – Click Here!

Comments (1) -

 Sean
Sean
2/13/2007 10:18:10 AM #

Not that the IsChanged property is a bad thing, but I'd personally add some events for acknowledging that something has changed.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.