C# Dynamic Array (ArrayList)

C# collections

ArrayList is a dynamic array class provided in C#, located in the System.Collections namespace.

Dynamic arrays (ArrayList) differ from ordinary arrays in that their size can be adjusted dynamically without needing to define a fixed length in advance.

Dynamic array (ArrayList) represents an ordered collection of objects that can be individually indexed, and it also allows dynamic memory allocation, addition, searching, and sorting of items within the list.

ArrayListThe class is suitable for array operations that require frequent resizing, but due to its non-generic nature, it is gradually being [replaced by List<T>] in modern C# development.List<T>replacement.

Basic Structure

public class ArrayList : ICollection, IEnumerable, IList, ICloneable

Implement interface:

  • Implement interface:
    • IList: Supports accessing elements by index.
    • ICollection: Supports basic collection operations, such as adding, removing, and counting.
    • IEnumerable: Supports iterating over elements via an enumerator.
    • ICloneable: Supports cloningArrayList。

Features

Dynamic extension:

  • ArrayListIts capacity can be automatically adjusted as needed, with no need to specify a fixed size.
  • When the number of added elements exceeds the current capacity,ArrayListIt automatically increases capacity (usually doubling the original capacity).

Non-generic collections:

  • ArrayListIt is a non-generic collection, and all elements are stored asobjecttype. This means it can store objects of any type, but attention should be paid to the performance impact of boxing and unboxing.

Unordered operation:

  • Although the order of element storage is the same as the order of addition, it does not provide built-in sorting functionality.

Thread Safety:

  • It is not thread-safe by default. If a thread-safe [implementation is needed],ArrayList, can useArrayList.SynchronizedThe method creates a thread-safe version.

Methods and properties of the ArrayList class

The table below listsArrayListSome common uses of the classProperty:

Attribute NameTypeDescription
CountintGetArrayListThe number of elements contained.
CapacityintGet or setArrayListThe capacity (storage space).
IsFixedSizeboolIndicateArrayListWhether it has a fixed size.
IsReadOnlyboolIndicateArrayListWhether it is read-only.
IsSynchronizedboolIndicateArrayListWhether it is thread-safe.
SyncRootobjectGets an object that can be used for synchronized access.

The table below listsArrayListSome common uses of the classMethods:

Method NameReturn TypeDescription
Adding and inserting
Add(object value)intAdd the object toArrayListAt the end, returns the index of the new element.
AddRange(ICollection c)voidAdds all elements of the specified collection toArrayListthe end.
Insert(int index, object value)voidInserts an object at the specified index.
InsertRange(int index, ICollection c)voidInserts all elements of the specified collection at the specified index.
Delete
Remove(object value)voidRemoves the first occurrence of the specified object.
RemoveAt(int index)voidRemoves the element at the specified index.
RemoveRange(int index, int count)voidRemoves a specified number of elements starting from the specified index.
Clear()voidRemove all elements.
Accessing and querying
Contains(object item)boolDecision MakingArrayListWhether it contains the specified object.
IndexOf(object value)intGets the index of the first occurrence of the specified object.
LastIndexOf(object value)intGets the index of the last occurrence of the specified object.
Sorting and copying
Sort()voidSorts in the default order.ArrayListThe elements inside.
Sort(IComparer comparer)voidSorts according to a custom comparer.
Reverse()voidReverseArrayListThe order of elements in
CopyTo(Array array)voidwillArrayListCopy the elements to the specified array.
Other
GetRange(int index, int count)ArrayListGets a subset of a specified number of elements starting from the specified index.
ToArray()object[]willArrayListCopy the elements in to the array.
TrimToSize()voidAdjusts the capacity to the actual number of elements to save memory.

Example

The following example demonstrates the concept of dynamic arrays (ArrayList):

Example

using System;
using System.Collections;

namespace CollectionApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a dynamic array and initialize it
            ArrayList numbers = InitializeArrayList();

            // Display the array's capacity and element count
            DisplayArrayListInfo(numbers);

            // Display array contents
            Console.Write("Original Content: ");
            DisplayArrayListContent(numbers);

            // Sort the array contents
            numbers.Sort();

            // Display sorted content
            Console.Write("Sorted Content: ");
            DisplayArrayListContent(numbers);

            Console.ReadKey(); // Wait for user to press a key to exit
        }

        /// <summary>
        /// Initialize and populate the ArrayList
        /// </summary>
        /// <returns>An ArrayList containing the initial data</returns>
        static ArrayList InitializeArrayList()
        {
            ArrayList al = new ArrayList();
            Console.WriteLine("Adding numbers to the ArrayList:");
           
            // Add initial elements
            int[] initialNumbers = { 45, 78, 33, 56, 12, 23, 9 };
            foreach (int num in initialNumbers)
            {
                al.Add(num);
                Console.WriteLine($"Added: {num}");
            }

            return al;
        }

        /// <summary>
        /// Display the capacity and element count of ArrayList
        /// </summary>
        /// <param name="al">ArrayList object</param>
        static void DisplayArrayListInfo(ArrayList al)
        {
            Console.WriteLine($"\nCapacity: {al.Capacity}"); // current capacity
            Console.WriteLine($"Count: {al.Count}");         // Current element count
        }

        /// <summary>
        /// Display the contents of the ArrayList
        /// </summary>
        /// <param name="al">ArrayList object</param>
        static void DisplayArrayListContent(ArrayList al)
        {
            foreach (int num in al)
            {
                Console.Write(num + " ");
            }
            Console.WriteLine(); // newline
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Adding numbers to the ArrayList:
Added: 45
Added: 78
Added: 33
Added: 56
Added: 12
Added: 23
Added: 9

Capacity: 16
Count: 7
Original Content: 45 78 33 56 12 23 9 
Sorted Content: 9 12 23 33 45 56 78 

and generic collectionsList<T>comparison

FeaturesArrayListList<T>
Type SafetyNo (storageobjecttype)Yes (generic, strongly typed constraint)
Boxing and unboxingYes (required for value types)no
PerformanceRelatively LowHigher
Generic supportNoneYes
Use CaseLegacy code or simple scenariosPreferred in modern development

Notes

Avoid frequent boxing and unboxing:

  • If the data mainly consists of value types, it is recommended to use [List<T>]List<T>to avoid performance overhead.

Use mixed-type data with caution.:

  • Try not to mix and store objects of different types, so as to reduce the risk of runtime errors.

Alternative solution:

  • In modern C# development, it is recommended to use generic collections (such asList<T>、Dictionary<TKey, TValue>) to improve the safety and efficiency of the code.

C# collections

other extensions