Both lists and arrays store data in one object(array or list).

  1. In C# what is the difference between arrays and lists?
  2. Can we store the same type in a list as an array?
  3. Can an list store objects and references to other objects?
  4. Where would we use a list instead of an array or vise versa?
  5. What benefits does each have over the other?

In C# what is the difference between arrays and lists?

An array has a pre-defined size that cannot change. A list has a dynamic size.

Can we store the same type in a list as an array?

Yes.

Can an list store objects and references to other objects?

Of course. However, there's a caveat. For the generic list, the types must match the declaration.

Where would we use a list instead of an array or vise versa?

As a general practice, I prefer List<> over an array in all cases. That's not to say I don't use arrays, it's just not not my default choice. Typically I only use arrays when I have no choice, such as when an array is the return type of a method I don't control.

What benefits does each have over the other?

This is informative, and should get you started on further research.

  1. An array is fixed, to a list you can add and remove objects at will.
    I would typicaly use an array to describe the suits of a card game for instance.
  2. You can store the same type of object in an array or list.
  3. A list can be like List<string, int> myList; it is harder to do that with an array.
  4. Use a List if you are not sure how many objects you have. eg. a list of employee objects. Although you could do that with an array,if you hire an exrtra employee yu haven to chage your array. There are only 4 suits in a card game so you could use an array.
  5. Read the above.

A list can be like List<string, int> myList; it is harder to do that with an array.

That's not a legal declaration. List<> only supports a single generic type. Of course, you can use an aggregate type or any type that holds multiple values. A relatively common thing I do for multiple related types is:

List<KeyValuePair<string, int>> myList;

Or:

List<Tuple<string, int, double>> myList;

In some cases using a static size can bring about an increased efficiency in terms of speed. While this can be done with a list, to many people, it's less intuitive than an array and not always as efficient. For instance in my experiments with the Sieve of Eratosthenes, I found a boolean array(bool[]) to out perform a list of boolean(List<bool>).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.