C# ArrayList

An ArrayList is a dynamic list that can grow and shrink as you add or remove items. Unlike regular arrays, you do not set the size in advance. It belongs to the System.Collections namespace and stores elements of any type.

Array vs ArrayList

┌──────────────────────────────┬──────────────────────────────┐
│ Regular Array                │ ArrayList                    │
├──────────────────────────────┼──────────────────────────────┤
│ Fixed size — set at creation │ Dynamic — grows/shrinks      │
├──────────────────────────────┼──────────────────────────────┤
│ One data type only           │ Stores any type (object)     │
├──────────────────────────────┼──────────────────────────────┤
│ int[] arr = new int[5];      │ArrayList list=new ArrayList()│
├──────────────────────────────┼──────────────────────────────┤
│ Faster — no type conversion  │ Slower — boxing/unboxing     │
└──────────────────────────────┴──────────────────────────────┘

Creating an ArrayList

using System;
using System.Collections;

ArrayList list = new ArrayList();

Adding Items

Use Add() to append an item. The ArrayList accepts any type.

ArrayList items = new ArrayList();

items.Add("Apple");
items.Add(42);
items.Add(3.14);
items.Add(true);

// The list now holds:  ["Apple", 42, 3.14, true]
// All four have different types — this is allowed

ArrayList Memory Growth Diagram

┌───────────────────────────────────────────────────────────┐
│  Start: capacity = 4 (default)                            │
│  [_][_][_][_]                                             │
│                                                           │
│  After Add("Apple"):                                      │
│  [Apple][_][_][_]                                         │
│                                                           │
│  After Add(42):                                           │
│  [Apple][42][_][_]                                        │
│                                                           │
│  After Add(3.14), Add(true):                              │
│  [Apple][42][3.14][true]                                  │
│                                                           │
│  When full and you add more → capacity doubles to 8       │
└───────────────────────────────────────────────────────────┘

Accessing Items

Access elements by index, just like a regular array. Indices start at 0. Note that items come back as object type — you must cast them to the original type.

ArrayList fruits = new ArrayList();
fruits.Add("Apple");
fruits.Add("Mango");
fruits.Add("Banana");

Console.WriteLine(fruits[0]);   // Apple
Console.WriteLine(fruits[1]);   // Mango

// Cast to string when needed:
string name = (string)fruits[2];
Console.WriteLine(name.ToUpper());  // BANANA

Removing Items

Remove by value:

fruits.Remove("Mango");    // removes "Mango"

Remove by index:

fruits.RemoveAt(0);        // removes item at index 0

Remove a range:

fruits.RemoveRange(0, 2);  // removes 2 items starting at index 0

Inserting Items

Use Insert() to add an item at a specific position. All items after that position shift to the right.

ArrayList nums = new ArrayList() { 10, 30, 40 };
nums.Insert(1, 20);   // insert 20 at index 1

// Before: [10, 30, 40]
// After:  [10, 20, 30, 40]

// Diagram:
// Before Insert(1, 20):
//   [10] [30] [40]
//    0    1    2
//
// After Insert(1, 20):
//   [10] [20] [30] [40]
//    0    1    2    3
//        ↑
//   20 inserted here; 30 and 40 shifted right

Checking and Searching

ArrayList colors = new ArrayList() { "Red", "Green", "Blue" };

// Check if item exists:
Console.WriteLine(colors.Contains("Green"));   // True
Console.WriteLine(colors.Contains("Yellow"));  // False

// Find index of item:
Console.WriteLine(colors.IndexOf("Blue"));     // 2

// Total items:
Console.WriteLine(colors.Count);               // 3

Sorting and Reversing

Sort() and Reverse() work only when all items in the ArrayList are the same comparable type (like all strings or all integers).

ArrayList scores = new ArrayList() { 45, 90, 12, 67, 33 };
scores.Sort();
// [12, 33, 45, 67, 90]

scores.Reverse();
// [90, 67, 45, 33, 12]

ArrayList words = new ArrayList() { "Banana", "Apple", "Cherry" };
words.Sort();
// [Apple, Banana, Cherry]

Looping Through an ArrayList

ArrayList animals = new ArrayList() { "Cat", "Dog", "Bird" };

// Using foreach:
foreach (object animal in animals)
{
    Console.WriteLine(animal);
}

// Using for loop with Count:
for (int i = 0; i < animals.Count; i++)
{
    Console.WriteLine(animals[i]);
}

Clearing an ArrayList

animals.Clear();
Console.WriteLine(animals.Count);  // 0

Boxing and Unboxing

ArrayList stores everything as object. When a value type (like int) goes in, it gets wrapped (boxed). When it comes out, it must be unwrapped (unboxed). This is slower than typed collections.

┌────────────────────────────────────────────────────────────┐
│              BOXING / UNBOXING DIAGRAM                     │
├────────────────────────────────────────────────────────────┤
│                                                            │
│  int num = 42;                                             │
│  list.Add(num);                                            │
│         │                                                  │
│         ▼  Boxing (int → object)                           │
│  [ object: 42 ]  ← stored in heap as object                │
│                                                            │
│  int result = (int)list[0];                                │
│         │                                                  │
│         ▲  Unboxing (object → int)                         │
│  result = 42                                               │
│                                                            │
└────────────────────────────────────────────────────────────┘

ArrayList vs List<T>

Modern C# code prefers List<T> (a generic list) over ArrayList. It is type-safe and avoids boxing/unboxing. ArrayList is still used in older codebases.

┌────────────────────────┬──────────────────────────────────────┐
│ ArrayList              │ List<T>                              │
├────────────────────────┼──────────────────────────────────────┤
│ Stores object type     │ Stores specific type T               │
├────────────────────────┼──────────────────────────────────────┤
│ Boxing/unboxing needed │ No boxing — already typed            │
├────────────────────────┼──────────────────────────────────────┤
│ No type safety         │ Full type safety                     │
├────────────────────────┼──────────────────────────────────────┤
│ System.Collections     │ System.Collections.Generic           │
├────────────────────────┼──────────────────────────────────────┤
│ Use for legacy code    │ Use for all new code                 │
└────────────────────────┴──────────────────────────────────────┘

Quick Method Reference

┌────────────────────────┬──────────────────────────────────────┐
│ Method/Property        │ What It Does                         │
├────────────────────────┼──────────────────────────────────────┤
│ Add(item)              │ Append item to end                   │
│ Insert(index, item)    │ Add item at position                 │
│ Remove(item)           │ Remove first match by value          │
│ RemoveAt(index)        │ Remove item at index                 │
│ RemoveRange(i, count)  │ Remove multiple items                │
│ Contains(item)         │ Check if item exists                 │
│ IndexOf(item)          │ Find position of item                │
│ Sort()                 │ Sort items in place                  │
│ Reverse()              │ Reverse order                        │
│ Clear()                │ Remove all items                     │
│ Count                  │ Number of current items              │
│ Capacity               │ Current buffer size                  │
└────────────────────────┴──────────────────────────────────────┘

ArrayList is a great stepping stone to understanding how dynamic collections work in C#. Once you grasp it, the jump to the more powerful and safer List<T> becomes very straightforward.

Leave a Comment

Your email address will not be published. Required fields are marked *