ArrayList vs List in C#

 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

  1. Type Safety:

    • ArrayList is not type-safe as it stores items as object. 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.
  2. 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.
  3. Usage:

    • ArrayList is part of the System.Collections namespace.
    • It is considered obsolete for new development in favor of List<T> and other generic collections.

List<T>

  1. 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.
  2. 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.
  3. Usage:

    • List<T> is part of the System.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> over ArrayList for new development as ArrayList 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.

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form