How to populate an ArrayList collection in C#

An ArrayList is a nongeneric C# collection that can store elements of any type. As the name shows, it's an array-like data structure capable of dynamically expanding or shrinking as required. To populate an ArrayList, we can use the following methods:

  • Add(): To add individual elements

  • AddRange(): To add multiple elements at once

Syntax

The syntax for initializing and populating an ArrayList using Add and AddRange is given below:

ArrayList myList = new ArrayList();
// Adding individual elements
myList.Add(element1);
myList.Add(element2);
myList.Add(element3);
// Adding multiple elements using collection initializer
myList.AddRange(collection = new[]{element4, element5});

The Add() method takes a single parameter (element) and adds it to the end of myList. On the other hand, the AddRange() method takes a collection of elements and appends them at the end of myList.

Note: The AddRange() method is more efficient than the Add() method when adding multiple elements as it saves redundant method calls.

Example

Let's look at an example demonstrating how to populate an ArrayList with the names of students:

using System;
using System.Collections;
class Collection
{
static void Main()
{
ArrayList students = new ArrayList();
// Adding individual elements
students.Add("Alice");
students.Add("Bob");
students.Add("Carol");
// Adding multiple elements using
// Collection initializer
students.AddRange(new[] { "Jane", "Doe" });
// Accessing elements
Console.WriteLine("Students:");
foreach (var student in students)
{
Console.WriteLine(student);
}
}
}

Output

The code above will generate the following output:

Students:
Alice
Bob
Carol
Jane
Doe

Explanation

We can review the line-by-line breakdown of the code above:

  • Line 2: We import the System.Collections namespace to access the ArrayList class.

  • Line 8: We create an instance of the ArrayList named students.

  • Lines 11–13: We use the Add() method to add individual elements to the ArrayList: Alice, Bob, and Carol.

  • Line 17: We use the AddRange() method to add multiple elements at once. We use the collection initializer syntax to provide a set of elements, i.e., Jane and Doe.

  • Lines 21–23: We iterate over the students to access and print each element using a foreach loop.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved