views:

142

answers:

5

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.

A: 

I would only use an array if your collection is immutable.

Edit: Immutable in a sense that your collection will not grow or shrink.

someguy
Arrays do not provide immutable collections. The value of any element of array can be modified using the index.
Yogendra
@Yogendra I think you just about missed my edit when posting.
someguy
@Someguy, yeah I think :).
Yogendra
+5  A: 

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.

Justin Niessner
+1  A: 

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
});
Guffa
A: 

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.

Justin
+2  A: 

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
    }
Dr. Wily's Apprentice