Each ArrayList element is an object. ArrayList simply stores object references. Thus you can store a value type into an ArrayList, however, you have to incur box/unbox while accessing those value type.
Exception could happen if the object to be added has a wrong type.
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
}
You can use List<T> to avoid above error.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;
}
ArrayList now is replaced with List<T>.List<T>
is a generic class. It supports stores value type without casting. As a generic collection, it implements the generic IEnumerable<T>
interface and can be used easily in LINQ.Source: http://stackoverflow.com/questions/2309694/arraylist-vs-list-in-c-sharp
No comments:
Post a Comment