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 elementsAddRange(): 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 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.
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 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);}}}
Output
The code above will generate the following output:
Students:AliceBobCarolJaneDoe
Explanation
We can review the line-by-line breakdown of the code above:
Line 2: We import the
System.Collectionsnamespace to access theArrayListclass.Line 8: We create an instance of the
ArrayListnamedstudents.Lines 11–13: We use the
Add()method to add individual elements to theArrayList:Alice,Bob, andCarol.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.,JaneandDoe.Lines 21–23: We iterate over the
studentsto access and print each element using aforeachloop.
Free Resources