Sunday, January 22, 2006

What's wrong with System.Collections.Generic

Generics are great. The first thing that you will want to use them for are collections and that's for sure. At last you can get rid of all the XXXXCollection classes that most of the time were just a wrapers around ArrayList. Yeap, generics are really great, but lets look at System.Collections.Generic namespace. Most interfaces look similar to their 1.1 equivalents, but ICollection is quite different than ICollection.
ICollection is basically IEnumerable + Count and CopyToArray, so I used to use it whenever I wanted to give a client of my code a read-only
access to a collection of items.
ICollection is different. In addition to the features of ICollection it adds Add(T), Remove(T) and Clear() methods, so it no longer represents a readonly collection of items. What about ICollection.ReadOnly property you will ask... Ok, it is there but what happens to ICollection when ReadOnly == true? Answer: a half of its methods will throw InvalidOperationException. I don't like it... If you want it to be read-only expose the interface that will clearly comunicate your intension and does not allow modifications.
Ok, if I don't like sth I look for an alternatives. So I googled around for a third party collections libraries and found PowerCollections (http://www.wintellect.com/powercollections/) and C5 collection library (http://www.itu.dk/research/c5/). While PowerCollections complements rather than replaces System.Collections.Generic namespace, C5 library can be used as a complete replacement of the standard collections library.
What I like the most about C5 is that it introduces fine grained Interfaces representing various features of a collection. To name a few:

ICollectionValue : IEnumerable - readonly collection with featues such as Count, FindAll, ToArray, etc.

IExtensible : ICollectionValue - collection that allows adding items

ICollection : IExtensible - fully flagged collection with all (and a few extra) the features of System.Collections.Genric.ICollection

I havent used C5 in any serious development (not only because it is in prelease version and the home bage haven't been modified since 2004) but I like many of the ideas implemented in it.

1 comment:

Anonymous said...

I'm happy to report that we haven't been idle since 2004, and that the C5 generic collection library is now available for .Net 2.0, including extensive documentation in the form of a free book at the website http://www.itu.dk/research/c5/