Are you sure you want List? Maybe you really want HashSet
I often find that I get so used to using List<T> for my collections that I forget to consider whether it is really the right tool for the job. If the collection is not ordered, and you don’t want duplicates then there are a lot of benefits to using HashSet<T>. For example with List<T> you’ll find yourself writing code like this:
if (!myCollection.Contains(newString))
{
myCollection.Add(newString);
}
This is a little verbose and it’s also inefficient. Every time you call Contains() the entire collection has to be scanned. With a HashSet<T> set operations are optimized and the code is simpler:
myHashSet.Add(newString);
The other benefit is that you actually enforce the no duplicate rule since adding the same element more than once will have no effect. Here’s what the MSDN documentation says about HashSet<T>:
The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
In practice I am finding that there are actually a lot of scenarios when I really want a set and not a list. So the next time you create a collection, think about whether you can use a HashSet.
Good call. I also find a lot of places where someone will use a List out of habit when all they really need is IEnumerable. List exposes your collection to the consumer in ways that maybe you didn’t want to allow. Being able to change the collection out from underneath isn’t always desirable
That’s an excellent point and I hadn’t really thought about it much, but it can definitely be problematic if client code can add new elements to the collection when it isn’t supposed to. On the other hand, I have often found myself specifically using List instead of IEnumerable even though I don’t want List functionality because of this issue: http://graemehill.ca/linq-queries-return-queries-not-data (I explain the problem with IEnumerable in the last paragraph). Basically, if you have an object of type IEnumerable all you know is that it is enumerable (duh) but you don’t know if it has been evaluated yet (it could be lazy loaded data from an ORM). If you use list at least you know that when you try to examine the collection it won’t hit the database or anything. Ideally there would be a happy medium, like IPreloadedEnumerable or something.