What's missing from this strategy of choosing which C# collection to use?
Asked Answered
P

3

7

Here's my strategy for choosing which C# collection type to use:

  • if number of items in collection is fixed, then use an array, e.g.:

    string[] directions = new string[] { "north", "south", "east", "west" };

  • otherwise always use List<T>

  • unless of course you need a more specialized collection, e.g. Stack<T>, Queue<T>, or Dictionary<TKey, TValue>

  • but never use ArrayList anymore

Based on your experience, what is missing from this strategy?

Piccolo answered 8/8, 2010 at 20:14 Comment(5)
Not overly sure why this is community wiki?Postfree
I thought it was good etiquette to mark opinion questions as community wiki. There really isn't a specific answer to this question, I just to want put my strategy out there and see based on experience of others, if there is anything missing that I should know.Piccolo
My take on it is that if there are demonstrably wrong answers, it doesn't belong as community wiki.Attaway
sadly, it is not possible to undo a community wiki: meta.stackexchange.com/questions/6821/…Piccolo
I pretty much never use arrays (T[]) - List<T> is my default even for fixed size collections.Groark
V
7

Your rules work fine.

In addition:

  • Always perfer generic (or specialized) collections over ungeneric (object-based) ones.
  • Use HashSet<T> if you want to check for mere existence instead of key-value-mappings (which is represented through Dictionary).
  • In case of dictionaries, consider the use of ordered maps (SortedList<...>, SortedDictionary<...>) if ordering seems important.
  • Use linked lists if you have remove/insert operations in the middle.

and of course the most important one:

  • Never export concrete collection types: Always use the most general interface, which is - in the most cases - IList<T> or IEnumerable<T>.
Vernal answered 8/8, 2010 at 20:14 Comment(0)
P
5

I'd say that in the majority of cases, even if I knew the number of items in a collection, I'd use List, simply for the number of utility functions it provides and compatibility with LINQ.

Hashmaps are an important use case, for when you would want faster access to items within the collection.

Postfree answered 8/8, 2010 at 20:14 Comment(0)
T
1

You can also use Collection<T> if you plan to override add/remove/clear methods in an inherited class because there are virtual methods.

Toxinantitoxin answered 8/8, 2010 at 20:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.