Possible Duplicates:
c# array vs generic list
Array versus List<T>: When to use which?
I understand that there are several benefits of using List<>. However, I was wondering what benefits might still exist for using arrays.
Thanks.
Possible Duplicates:
c# array vs generic list
Array versus List<T>: When to use which?
I understand that there are several benefits of using List<>. However, I was wondering what benefits might still exist for using arrays.
Thanks.
I would only use an array if your collection is immutable.
Edit: Immutable in a sense that your collection will not grow or shrink.
You'll have a simple static structure to hold items rather than the overhead associated with a List (dynamic sizing, insertion logic, etc.).
In most cases though, those benefits are outweighed by the flexibility and adaptability of a List.
An array is simpler than a List, so there is less overhead. If you only need the capabilities of an array, there is no reason to use a List instead.
The array is the simplest form of collection, that most other collections use in some form. A List actually uses an array internally to hold it's items.
Whenever a language construct needs a light weight throw-away collection, it uses an array. For example this code:
string s = "Age = " + age.ToString() + ", sex = " + sex + ", location = " + location;
actually becomes this code behind the scene:
string s = String.Concat(new string[] {
"Age = ",
age.ToString(),
", sex = ",
sex,
", location = ",
location
});
Speed would be the main benefit, unless you start writing your own code to insert/remove items etc.
A List uses an array internally and just manages all of the things a list does for you internally.
One thing arrays have over lists is covariance (http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29).
class Person { /* ... */}
class Employee : Person {/* ... */}
void DoStuff(List<Person> people) {/* ... */}
void DoStuff(Person[] people) {/* ... */}
void Blarg()
{
List<Employee> employeeList = new List<Employee>();
// ...
DoStuff(employeeList); // this does not compile
int employeeCount = 10;
Employee[] employeeArray = new Employee[employeeCount];
// ...
DoStuff(employeeArray); // this compiles
}