Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic List vs Array [duplicate]

Tags:

c#

Possible Duplicate:
Array versus List<T>: When to use which?

Is there any best practice or rule of thumb when to use a list vs an array? For example, a tutorial I am following uses arrays to hold some data, and he is always saying "Oh an array of 40 will be enough because I am never going to use more than that.

However, I have swapped out his arrays for Lists. That way the size of the list can adjust to my needs at run time, and it also allows me to use the IEnumerable iterator so I can use for each loops.

So, is there any downsize to using a List? I am guessing its more of a performance hit than using arrays, but is it significant? Should I try and use Arrays more often or go with Lists and only use arrays if I notice a performance issue?

like image 756
Terry Avatar asked Dec 29 '22 09:12

Terry


2 Answers

Lists are usually the way to go, unless as you say, that you need to squeeze more performance:

  • Array versus List<T>: When to use which?

and

  • Performance of Arrays vs. Lists

When exposing lists to consumers, remember to pick an appropriate Interface (i.e. expose IList, ICollection or IEnumerable, not List<T>, depending on the minimum contract you wish to guarantee to the consumer), as per this discussion here: IList vs IEnumerable for Collections on Entities

like image 137
StuartLC Avatar answered Jan 12 '23 02:01

StuartLC


I'd recommend looking at this SO answer.

like image 45
Matthew Abbott Avatar answered Jan 12 '23 03:01

Matthew Abbott