What is the difference between ArrayList
and List<>
in C#?
Is it only that List<>
has a type while ArrayLis
Using List
you can prevent casting errors. It is very useful to avoid a runtime casting error.
Example:
Here (using ArrayList
) you can compile this code but you will see an execution error later.
ArrayList array1 = new ArrayList();
array1.Add(1);
array1.Add("Pony"); //No error at compile process
int total = 0;
foreach (int num in array1)
{
total += num; //-->Runtime Error
}
If you use List
, you avoid these errors:
List list1 = new List();
list1.Add(1);
//list1.Add("Pony"); //<-- Error at compile process
int total = 0;
foreach (int num in list1 )
{
total += num;
}
Reference: MSDN