Which is better to use array or List<>?
.net, c#, collections, performance
Solution
More context is really required to answer the question properly:
In a public API, you should try to use abstract collection types, so that you can change the internal implementation later if you need to.
- If the collection should not be changed by the outside world, use `IEnumerable<T>`.
- If the collection will be changed by the outside world, use `ICollection<T>`.
- If indexed access is required, use `IList<T>`.
In a private implementation, it's not as important to use the abstract types:
- If you need indexed access and know the final size, use `T[]` or `List<T>`.
- If you need indexed access and don't know the final size, use `List<T>`.
- If you plan to access elements in a LIFO pattern, use `Stack<T>`.
- If you plan to access elements in a FIFO pattern, use `Queue<T>`.
- If you need to access elements at the beginning and end of the list, but not in the middle, use `LinkedList<T>`.
- If you don't want duplicates, use `HashSet<T>`.
In .NET 4.0 you have a few more choices, but those are the basics.
Problem
I was wondering which type would have better performance and which you think should be used. For example I have a List of strings not knowing how many items I will need so having the .Add(String) function is really convenient. I can Add new strings to the list at any time easily. What are the advantages/disadvantages of using each? Are lists the new arrays?