Alex Rivera | Logout

c# array vs generic list

Asked 2010-03-12T06:18:28.763
33

i basically want to know the differences or advantages in using a generic list instead of an array in the below mentioned scenario

class Employee
{
    private string _empName;

    public string EmpName
    {
       get{ return _empName; }
       set{ _empName = value; }
    }
}

1. Employee[] emp 
2. List<Employee> emp

can anyone please tell me the advantages or disadvantages and which one to prefer?

Edit
Report

3 Answers

7

With the generic list, you can Add / Remove etc cheaply (at least, at the far end). Resizing an array (to add/remove) is more expensive. The obvious downside is that a list has spare capacity so maybe wastes a few bytes - not worth worrying about in most cases, though (and you can trim it).

Generally, prefer lists unless you know your data never changes size.

API-wise, since LINQ there is little to choose between them (i.e. the extra methods on List<T> are largely duplicated by LINQ, so arrays get them for free).

Another advantage is that with a list you don't need to expose a setter:

private readonly List<Foo> items = new List<Foo>();
public List<Foo> Items { get { return items; } }

eliminating a range of null bugs, and allowing you to keep control over the data (especially if you use a different IList<> implementation that supports inspection / validation when changing the contents).

answered 2010-03-12T06:22:49.043
1

If you know the number of elements array is a good choice. If not use the list. Internally List<T> uses an array of T so the are actually more like than you may think.

answered 2010-03-12T06:22:12.257
1

With a List, you don't need to know the size of the array beforehand. You can dynamically add new Employee's based on the needs of your implementation.

answered 2010-03-12T06:22:31.850

Your Answer