In C#, both ArrayList
and List<T>
are used to store collections of objects, but they have significant differences in terms of performance, type safety, and usage. Here are the main differences:
ArrayList
Type Safety:
ArrayList
is not type-safe as it stores items asobject
. This means that it can store any type of object.- You need to cast objects back to their original type when retrieving them, which can lead to runtime errors.
Performance:
- Because
ArrayList
stores objects, boxing and unboxing occur when storing value types, which can impact performance. - It has slightly worse performance compared to
List<T>
due to the overhead of boxing and unboxing.
- Because
Usage:
ArrayList
is part of theSystem.Collections
namespace.- It is considered obsolete for new development in favor of
List<T>
and other generic collections.
List<T>
Type Safety:
List<T>
is type-safe because it uses generics. You specify the type of elements it can store when you declare it, providing compile-time type checking.- No need for casting when retrieving elements.
Performance:
List<T>
does not require boxing and unboxing, which improves performance, especially when dealing with value types.- Generally more efficient than
ArrayList
due to its type-specific implementation.
Usage:
List<T>
is part of theSystem.Collections.Generic
namespace.- It is the preferred collection for new development because of its type safety, performance, and flexibility.
Example Usage
ArrayList
using System;
using System.Collections;
public class Example
{
public static void Main()
{
ArrayList arrayList = new ArrayList();
arrayList.Add(1);
arrayList.Add("two");
arrayList.Add(3.0);
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
}
}
List
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
foreach (int item in list)
{
Console.WriteLine(item);
}
}
}
Key Takeaways
- Type Safety: Use
List<T>
for type-safe collections where the type of elements is known at compile-time. - Performance: Use
List<T>
for better performance, especially with value types, due to the avoidance of boxing and unboxing. - Legacy vs Modern: Prefer
List<T>
overArrayList
for new development asArrayList
is considered obsolete and less efficient.
In summary, List<T>
is generally the better choice for most use cases due to its type safety, performance benefits, and flexibility.