6
Bubbles
5y

In C# should I be using collections over normal arrays?

What’s the difference and what are the benefits of using collections?

Comments
  • 6
    Array is just a sequential memory location, that stores elements of the same type.
    A collection is a datastructure that abstracts the process of managing elements (calculating indices, resizing arrays, iterators, map-reduce, ...), And generalizes it with interfaces, so you can change the storage backend later on (eg. From ArrayList to LinkedList).
  • 1
    @metamourge oh I see. And this is coming from someone who’s honestly still relatively new to C#’s concepts but does LINQ have to do with Collections?
  • 1
    @Bubbles
    I'm not a C#-dev, but from what I know, LINQ can be applied to process elements of DS, that implement a certain interface.
  • 1
    @metamourge oh sorry for the confusion but thanks for the explanations!
  • 4
    LINQ can also query arrays to my knowledge.
  • 1
    @kescherRant I think it needs a collection but I could be completely wrong
  • 2
    @Bubbles I'm a C# dev and I think you are right.

    I rarely use arrays because of their fixed size.
  • 5
    Arrays have fixed size and don't give you methods for adding/removing items. Collections have more features and solve their specific tasks. List manages its own array inside and allows to add/insert/remove items and implements sorting. HashSet stores unique items and allows quickly check if an item is in collection. Dictionary stores (key, value) pairs. Every time you need a collection to store items you should choose the best option for your requirements
  • 5
    @Bubbles LINQ works with IEnumerable<T>. All collections including arrays implement this interface
  • 1
    @Gxost Thanks for replying what I wanted to reply.
    foreach loops only work with IEnumerables, too, so that's an indicator.
  • 3
    Arrays are for when you have a fixed amount of data, quantity known in advance, and not changing throughout the lifetime of the array. If that is not the case, use a List<T> or something else.

    LINQ is for performing queries and operations over any collection that implements IEnumerable<T> and/or IQueryable<T>. This will apply to almost all .NET collection types.
  • 1
    @Gxost @SomeNone thank you both for the explanations it helps a lot!
  • 1
    Arrays for fixed size data or for low level stuff (implementing your own data structures)

    Collections for general use
Add Comment