This tutorial is about array list in C#. The advantage ArrayList gets over array is that it can add, search, index and remove data in a collection
Don't forget to check out our site http://howtech.tv/ for more free how-to videos!
http://youtube.com/ithowtovids - our feed
http://www.facebook.com/howtechtv - join us on facebook
https://plus.google.com/103440382717658277879 - our group in Google+
Introduction
Array List in C# is used to overcome the limitations of an array. ArrayList class implements a collection of objects using an array whose size dynamically increases as required. The advantage ArrayList gets over array is that it can add, search, index and remove data in a collection.
Read through the step by step guide below and learn how to use arraylist in c#
Step 1: Adding namespace
The add method is used to add the elements to an Array List in C#. Since an ArrayList is a collection of objects, casting is compulsory. ArrayList is present in the namespace System.Collections. Hence you need to add the statement:
using System.Collections;
Step 2: Implementing ArrayList
The following code snippet shows the implementation of an ArrayList:
ArrayList list = new ArrayList();
list.Add("one");
list.Add("two");
you can keep adding elements to your collection. The objects are stored in a managed heap.
Step 3: Iterating ArrayList
You can use foreach statement to iterate through the array:
foreach(string i in list)
{
Console.Write("\t"+i);
}
Step 4: Insert Objects into ArrayList
You can also insert an element into the ArrayList at a specified index:
list.Insert(1, "three");
Remember that the index value of an ArrayList starts from 0.
Step 5: Remove Objects from ArrayList
The Remove and RemoveAt members delete data from an ArrayList. The RemoveAt method removes the element at the specified index of the ArrayList, while the Remove method removes the first occurrence of a specific object from the ArrayList:
list.Remove("three");
Conclusion
Once removing elements, you can always set the capacity to the actual number of elements in the ArrayList with the TrimToSize function:
list.TrimToSize();
The ArrayList in C# class offers a variety of properties and methods that you can work on with.