In this C# tutorial chapter, we will learn about Array List in C#. In C#, ArrayList is a non-generic collection, it is useful to store data of various data-type, one of the main advantage of using ArrayList is, size of ArrayList can grow and shrink dynamically. The ArrayList class is defined in the System.Collections
namespace.
As explained above ArrayList in C#, is basically a non-generic collection, that works like an array but provides the facilities such as dynamic resizing, adding and deleting elements from the collection, unlike array where we specify array size and cannot add elements more than specified size.
System.Collections
namespace.System.Collections.IList
interface using an array whose size is dynamically increased as required.Here is how to declare arraylist in C#
ArrayList arrayList = new ArrayList();
In the above code, we have declared arrayList as ArrayList, with an instance of arraylist class without specifying any size.
Although there are many methods, properties of ArraList in C#, I have mentioned few but mostly used methods and properties.
using System;
using System.Collections;
public class CsharpArrayListProgram
{
public static void Main()
{
ArrayList arrayList = new ArrayList();
// add elements in ArrayList
arrayList.Add("C#");
arrayList.Add("ASP.Net");
arrayList.Add("SQL");
//print initial arrayList
Console.WriteLine("Initial ArrayList:");
ShowArrayList(arrayList);
//remove element from arrayList
arrayList.RemoveAt(1); //remove element using Index
//print arrayList after deletion
Console.WriteLine("ArrayList After deletion:");
ShowArrayList(arrayList);
//Gets the number of elements actually contained in the ArrayList.
Console.WriteLine("Item count of arrayList: "+ arrayList.Count);
//Check if Element exists using .Contains
Console.WriteLine("Item 'C#' Exists in ArrayiList: "+ arrayList.Contains("C#"));
}
//print ArrayList item using foreach
public static void ShowArrayList(ArrayList list)
{
foreach(var item in list)
{
Console.WriteLine(item);
}
}
}
Output:
Initial ArrayList:
C#
ASP.Net
SQL
ArrayList After deletion:
C#
SQL
Item count of arrayList: 2
Item 'C#' Exists in ArrayiList: True
In the above program, we are initializing arrayList and then adding few elements.
We are printing values of ArrayList using foreach loop, we are also using various methods and properties in the above C# program.