Generic Fiddling
I spent an hour yesterday playing with generics to get my chops up a little better. After reading Krzystof Cwalina's post on the layout of the generic collections, I came up with this little gem:
public class UniqueCollection<T> : Collection<T>
{
protected override void InsertItem(int index, T item)
{
if (Contains(item))
throw new ArgumentException("collection already contains item", "item");
base.InsertItem(index, item);
}
protected override void SetItem(int index, T item)
{
T itemAtIndex = this[index];
for (int i = 0; i < Count; i++)
{
if (i == index)
continue;
if (itemAtIndex.Equals(this[i]))
throw new ArgumentException("collection already contains item", "item");
}
base.SetItem(index, item);
}
}
This is the basis of a simple collection that ensures that all elements (that implement Equals) are unique. At this point you can derive classes from this:
public class UniqueStringCollection : UniqueCollection<string> { }
Note that this implementation is not performant for large collections - there are better ways to guarantee uniqueness, but those depend on the problem domain.
Enjoy.