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?
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 throughDictionary
). - 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>
orIEnumerable<T>
.
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.
You can also use Collection<T>
if you plan to override add/remove/clear methods in an inherited class because there are virtual methods.
精彩评论