Tuesday 7 February 2017

ArrayList VS List<> in C#

ArrayList and List<> both are collections.
List<T> is a generic class collection of specific type, no need to casting while accessing.
List<T> implements IEnumerable<T>.

ArrayList is collection of any objects, need casting while accessing.

Example:


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<int> list1 = new List<int>();
list1.Add(1);
//list1.Add("Pony"); //<-- Error at compile process
int total = 0;
foreach (int num in list1 )
{
 total += num;
}