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
The syntax for initializing and populating an ArrayList
using Add
and AddRange
is given below:
ArrayList myList = new ArrayList();// Adding individual elementsmyList.Add(element1);myList.Add(element2);myList.Add(element3);// Adding multiple elements using collection initializermyList.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 theAdd()
method when adding multiple elements as it saves redundant method calls.
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 elementsstudents.Add("Alice");students.Add("Bob");students.Add("Carol");// Adding multiple elements using// Collection initializerstudents.AddRange(new[] { "Jane", "Doe" });// Accessing elementsConsole.WriteLine("Students:");foreach (var student in students){Console.WriteLine(student);}}}
The code above will generate the following output:
Students:AliceBobCarolJaneDoe
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