I often use an ArrayList
instead of a \'normal\' array[]
.
I feel as if I am cheating (or being lazy) when I use an ArrayList
,
In addition to Bob's and Frederick's response, I would like to point it out that while arrays have covariance, generic lists do not. For example, an array of type MyChildClass[]
can be easily casted to MyParentClass[]
, while List<MyChildClass>
cannot be casted to List<MyParentClass>
, at least not directly.
If you need covariance, either use arrays, use LINQ's Cast() method or some other means to cast each item individually or wait for C# 4.
Better still, wherever you use ArrayList
, use the List<T>
generic collection instead. It is more strongly typed than the former.
Fabulous Adventures In Coding has written a piece Arrays considered somewhat harmful. It's a really interesting read.
It's Like this.
using System;
using System.Collections;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//ArrayList
/*
An ArrayList doesn't use a LinkedList as the internal data structure! .we can store any type of objects
*/
ArrayList list = new ArrayList();
list.Add("1"); // not strongly type,you can enter any object types (int,string decimals, etc..)
list.Add(1);
list.Add(1.25);
//Array
/*
must declare length.
*/
string[] array = new string[3]; // you must declare object types
array[0] = "1";
//array[1] = 1; this get error becoz array is storngly typed. // this print empty value when you run it
array[2] = "stongly typed";
Console.WriteLine("------- ARRAYLIST ITEMS ---------");
foreach (var i in list) {
Console.WriteLine(i);
}
Console.WriteLine("--------- ARRAY ITEMS -----------");
foreach (var i in array)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
}
One other thought here is mutation; an array (T[]
) is fully mutable, and cannot be protected. List<T>
doesn't provide any useful extension points, but things like Collection<T>
(or many other IList<T>
implementations) allow you to add code, for example, to check items before they are added; likewise, you can have readonly IList<T>
implementations, which is useful for thread safety where immutability is desirable.
I tend to use arrays either in internal method logic (perhaps as a local variable), as params
arguments, or in a few highly optimised cases where I know the length of the items, and I know the code chooses not to mutate it (as a private field). Other than that, List<T>
etc tend to be more common, as they have much less overhead when adding/removing items.
Unless that part of the code is absolutely performance-critical, using ArrayList is perfectly fine.