Welcome to Atalasoft Community Sign in | Help

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)
            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. 


Published Friday, August 08, 2008 8:34 AM by Steve Hawley


Monday, August 18, 2008 2:40 PM by DotNetKicks.com

# Generic Fiddling

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Monday, August 18, 2008 3:17 PM by Judah

# re: Generic Fiddling

System.Collections.Generic.HashSet<T> does this already, no?

Monday, August 18, 2008 11:11 PM by ewbi

# re: Generic Fiddling

A quick solution, but as you mentioned not performant given the linear search in the underlying List[T].Contains method.  Also not flexible, as this same Contains method is pegged to T's default EqualityComparer.  There are alternatives in the FX, or if you'd like to explore a fast and flexible (but one-way) custom implementation, I wrote something up last year:


Anonymous comments are disabled