What is missing in this selection strategy, which C # collection to use?

Here is my strategy for choosing the type of use of C #:

  • if the number of elements in the collection is fixed, then use an array , for example:

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

  • otherwise always use List<T>

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

  • but never again use an ArrayList

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

+7
collections design c # data-structures conceptual
source share
3 answers

Your rules work fine.

Besides:

  • Always pass general (or specialized) collections to non-viable ( object ) collections.
  • Use HashSet<T> if you want to check only the existence, and not the mapping of key values ​​(which is represented through the Dictionary ).
  • For dictionaries, consider using ordered maps ( SortedList<...> , SortedDictionary<...> ) if ordering seems important.
  • Use linked lists if you have delete / paste operations in the middle.

and, of course, the most important:

  • Never export concrete collection types: always use the most common interface, which - in most cases - IList<T> or IEnumerable<T> .
+7
source share

I would say that in most cases, even if I knew the number of elements in the collection, I would use List, simply for the number of function functions that it provides, and LINQ compatibility.

Hashmaps are an important use case when you need faster access to items in a collection.

+5
source share

You can also use Collection<T> if you plan to override the add / remove / clean methods in the inherited class, since there are virtual methods.

+1
source share

All Articles