1

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.

Community
  • 1
  • 1
Jones
  • 299
  • 2
  • 5
  • 11
  • I believe those other two questions do not address my question. I'm seeking reasons to use an array. Those questions seem to advocate using a List for its widely known benefits, while I'm seeking reasons to use an array. – Jones May 20 '10 at 17:32

5 Answers5

5

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
  • 242,243
  • 40
  • 408
  • 536
4

One thing arrays have over lists is covariance.

    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
    }
Justin Grant
  • 44,807
  • 15
  • 124
  • 208
Dr. Wily's Apprentice
  • 10,212
  • 1
  • 25
  • 27
2

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
  • 687,336
  • 108
  • 737
  • 1,005
1

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
  • 7,144
  • 12
  • 43
  • 57
0

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
  • 4,434
  • 4
  • 28
  • 37