In C#, an ArrayList
stores elements of multiple data types whose size can be changed dynamically.
To create ArrayList
in C#, we need to use the System.Collections
namespace. Here is how we can create an arraylist in C#.
1 2 3 4 | // create an arraylist ArrayList myList = new ArrayList(); |
Here, we have created an arraylist named myList
.
Basic Operations on ArrayList
In C#, we can perform different operations on arraylists. We will look at some commonly used arraylist operations in this tutorial:
- Add Elements
- Access Elements
- Change Elements
- Remove Elements
Let’s see how we can perform these operations in detail!
Add Elements in ArrayList
C# provides a method Add()
using which we can add elements in ArrayList
. For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using System; using System.Collections; class Program { public static void Main() { // create an ArrayList ArrayList student = new ArrayList(); // add elements to ArrayList student.Add("Tina"); student.Add(5); } } |
In the above example, we have created an ArrayList
named student
.
Then we added "Tina"
and 5 to the ArrayList
using the Add()
method.
Other way to add Elements to ArrayList
Add Elements in an ArrayList using Object Initializer Syntax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System; using System.Collections; class Program { public static void Main() { // create an ArrayList using var ArrayList myList = new ArrayList() { "Pizza", 24, "Pen" }; // iterate through items for (int i = 0; i < myList.Count; i++) { Console.WriteLine(myList[i]); } } } |
Add Elements in an ArrayList at specified index
To add an element to a specified index in ArrayList
, we use the Insert()
method. For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using System; using System.Collections; class Program { public static void Main() { // create an ArrayList ArrayList myList = new ArrayList(); myList.Add("Jimmy"); myList.Add("Blake"); myList.Add("Taylor"); Console.WriteLine("Before Inserting: " + myList[1]); // insert "Tim" at first index position myList.Insert(1, "Tim"); Console.WriteLine("After Inserting: " + myList[1]); } } |
In the above example, we have inserted "Tim"
at the second index position using the Insert()
method.
Access ArrayList Elements
We use indexes to access elements in ArrayList
. The indexing starts from 0. For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | using System; using System.Collections; class Program { public static void Main() { // create an ArrayList ArrayList schoolDetails = new ArrayList(); schoolDetails.Add("Mary's"); schoolDetails.Add("France"); schoolDetails.Add(23); // access the first element Console.WriteLine("First element: " + schoolDetails[0]); // access the second element Console.WriteLine("Second element: " + schoolDetails[1]); } } |