Recently, I was asked “What are the various kinds of collections in .Net. And when do you use them?”
From the top my head I could recount Arrays, Lists, Linked Lists, Queues, Stacks and, completely forgot about dictionaries. All of these are collections of items of some kind. You can loop over the items and do something with each of them. But then why do you need so many kinds of collections? When is it appropriate to use a type and, more importantly, when is it not? These two are very important questions that determine the appropriateness of a collections types use.
Like most, well I would say everything, in software engineering – IT DEPENDS. Depends on what? Depends on what the purpose is. What is that you are trying to do? What is the problem you are trying to solve?
Arrays, for example, are allocated from a contiguous chunk of memory. If the process cannot find the required amount of contiguous space, a garbage collection might be triggered. And this will suspend the current tasks. I will not go into the details of garbage collector and the process of garbage collection here. Just pick up Jeffrey Richter’s CLR via C# for a very thorough treatment of the subject.
Items for lists, say for example linked lists, may be allocated on the heap and the appripriate pointers adjusted. This probably is a fast process but the entire list may be fragmented and when looping over the list items may present a performance degradation. I haven’t done any tests but this is my conjecture from reading up on the types.
So, you need to be cognizant of what exactly happens when you use a certain collection type and what your requirement is. If your solution involves copying lists t(I don’t mean the list item, but a list of items) to another and doing something with it, an array may not be an appropriate type to use because, chunks of memory are allocated, chunks that may need to be garbage collected if Gen0 is full.
The collection type you use is also determined by -
1. Do you want index based access?
2. Do you want to store the same type in your list type or are you going to store different types?
3. Does looping over items in your list result in boxing and unboxing of types in the list?
4. Do you want name/value pairs?
5. Do you want a First In First Out or Last In Last Out type of access?
So there you have it. I have attempted to provide a very high level view of some the collection types in .Net and when is it appropriate to use a given type.