Thursday, October 24, 2024

C# Difference between Array and ArrayList


In C#, an array and an ArrayList are both used to store and manipulate collections of elements, but they have significant differences in terms of functionality, performance, and usage.

1. Type and Performance:
  • Array: An array is a fixed-size collection of elements of the same type. Once created, its size cannot be changed. Array elements can be accessed by their index, making access very fast, but resizing requires creating a new array and copying the contents, which can be inefficient for large arrays.
  • ArrayList: An ArrayList is a dynamic collection that can grow or shrink in size as needed. It can hold elements of any type (as it's a collection of objects), but this requires boxing and unboxing operations, which can impact performance.

2. Type Safety:
  • Array: Arrays are strongly typed, meaning they can only hold elements of a specific type.
  • ArrayList: ArrayLists are not strongly typed and can hold elements of any type because they are based on the System.Object type.

3. Usage:
  • Array: Arrays are used when a fixed-size collection of elements is needed and when efficiency in accessing elements by index is important.
  • ArrayList: ArrayLists are useful when a dynamic collection is required, and the elements can be of varying types.

4. Resizing:
  • Array: The size of an array is fixed and cannot be changed after creation.
  • ArrayList: The size of an ArrayList can be dynamically adjusted using the Add, Remove, and RemoveAt methods.

Here's a simple example demonstrating the differences in usage:

using System;
using System.Collections;

public class Program
{
    public static void Main(string[] args)
    {
        // Array
        int[] arr = new int[5];  // Fixed size of 5
        arr[0] = 10;
        arr[1] = 20;

        // ArrayList
        ArrayList arrayList = new ArrayList();  // Dynamic size
        arrayList.Add(10);
        arrayList.Add("Hello");
    }
}

In modern C# development, ArrayList is typically not used much because newer collections like List<T> provide better type safety and performance, similar to arrays, while also allowing dynamic resizing.

No comments:

Post a Comment

Hot Topics