Junior
What is the difference between ArrayList and List in C#?
sobes.tech AI
Answer from AI
The differences between ArrayList and List in C# are as follows:
-
Typing:
ArrayListstores elements of typeobject(non-generic collection), which requires casting when retrieving elements and reduces type safety.List<T>is a generic collection (Tis a specified type), stores elements of a strictly defined type, ensuring type safety and eliminating the need for casting.
-
Performance:
- Adding and retrieving elements in
ArrayListcan be slower due to boxing and unboxing of value types. List<T>is generally faster, especially for value types, as it avoids boxing/unboxing.
- Adding and retrieving elements in
-
Type Safety:
ArrayListcan contain elements of different types, which may lead to runtime errors.List<T>provides compile-time type safety.
-
Implementation:
ArrayListresides in theSystem.Collectionsnamespace.List<T>resides in theSystem.Collections.Genericnamespace.
-
Usage:
ArrayListis considered obsolete and is not recommended for use in new code.List<T>is the preferred choice for most scenarios.
Example usage:
// Using ArrayList
System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
arrayList.Add(1); // int is boxed into object
arrayList.Add("string"); // string is stored as object
int number = (int)arrayList[0]; // Casting is required
// Using List<T>
System.Collections.Generic.List<int> list = new System.Collections.Generic.List<int>();
list.Add(1); // Adding int
// int number = list[0]; // No casting needed
Comparison table:
| Attribute | ArrayList | List<T> |
|---|---|---|
| Typing | Non-typed (object) | Generic (T) |
| Performance | Possible boxing/unboxing | Higher, no boxing/unboxing for value types |
| Type Safety | Low | High (at compile time) |
| Namespace | System.Collections | System.Collections.Generic |
| Recommendation | Not recommended | Recommended |