DEV Community

Hassan BOLAJRAF
Hassan BOLAJRAF

Posted on

C# | Difference Between Array and ArrayList

Note
You can check other posts on my personal website: https://hbolajraf.net

In C#, both arrays and ArrayLists are used to store collections of elements, but they have different characteristics and behaviors. Let's explore the differences between them with detailed examples.

Arrays

Arrays are fixed-size data structures that store elements of the same type in contiguous memory locations. Once an array is created, its size cannot be changed.

Example of Array in C

// Declaring an array of integers with a fixed size of 5
int[] numbers = new int[5];

// Initializing array elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Accessing array elements
Console.WriteLine(numbers[2]); // Output: 30
Enter fullscreen mode Exit fullscreen mode

Characteristics of Arrays

  • Fixed size: The size of an array is determined at compile time and cannot be changed at runtime.
  • Type-safe: Arrays can only store elements of the same type.
  • Better performance: Arrays offer better performance in terms of accessing elements because they store elements in contiguous memory locations.

ArrayLists

ArrayLists are dynamic collections that can grow or shrink in size dynamically. They can store elements of different types and automatically resize themselves as needed.

Example of ArrayList in C

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        // Creating an ArrayList
        ArrayList list = new ArrayList();

        // Adding elements to the ArrayList
        list.Add(10);
        list.Add("Hello");
        list.Add(3.14);

        // Accessing elements in the ArrayList
        Console.WriteLine(list[1]); // Output: Hello

        // Iterating through the ArrayList
        foreach (var item in list)
        {
            Console.WriteLine(item);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Characteristics of ArrayLists

  • Dynamic size: ArrayLists can grow or shrink in size dynamically as elements are added or removed.
  • Heterogeneous elements: ArrayLists can store elements of different types.
  • Slower performance: ArrayLists may have slower performance compared to arrays because they involve additional overhead for resizing and boxing/unboxing operations.

What Next?

Both arrays and ArrayLists have their own advantages and use cases. Arrays are suitable for situations where the size of the collection is known and fixed, and when performance is critical. ArrayLists, on the other hand, are more flexible and convenient for scenarios where the size of the collection may change dynamically or when storing elements of different types. Choose the appropriate data structure based on the specific requirements of your application.

Top comments (1)

Collapse
 
axorax profile image
Axorax

great article!