To List<T> or to Collection<T>

15 במאי 2008

תגיות: , ,
אין תגובות

Pop quiz. how can tell me what is the difference between List<T> and Collection<T>? And even more important question "Which is the preferred implementation of a generic list these days?"

from a quick look at the classes one can see that Collection<T> is some sort of a customizable wrapper for List<T>… Collection<T> gives more for use as a base class where you can hook the "standard collections" like Insert, Remove, Clear, Set and such. . . This will give you the option to customize these methods according to your needs.  Internally, it's Items property is backed by a List<T>.

where List<T> is a read-to-declare-and-use dynamic array of T's, it is represents a collection of objects that can be individually accessed by index. While Collection<T> defines methods to manipulate generic collections.

According to FxCop, List<T> should only be used as an implementation detail, and never be exposed in an API, since you can't easily extend List<T> after the fact. While List<T> isn't sealed, it has absolutely no extensibility points.

Personally, while I never publicly expose properties or methods of type List<T>, I often declare them as IList<T> and implement them using List<T>. This provide the best of both worlds.

When creating your own "collection" class:

  • Base class for your custom collection classes Should be Collection<T>
  • For internal implementation (private fields and local variables) use – List<T>
  • External interface (public properties, methods, and collections) use – IList<T>, ICollection<T> and a good practice will be to use IEnumerable<T>

 

But let's not forget the other collections type and I certainly do not want to limit to just choosing between Collection<T> and List<T>… remember to consider Dictionary<TKey, TValue> or KeyedCollection<TKey, TItem>, or HashSet<T> if you're collecting things with identity where duplicates shouldn't be allowed, or where fast lookup by key is required or will perform a lot better than linearly searching a list.

 

Any Feedback or ideas?

(It took me about 35 min to write this post.)

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *