The Wayback Machine - https://web.archive.org/web/20240912005829/https://www.geeksforgeeks.org/arraylist-in-c-sharp/
Open In App

ArrayList in C#

Last Updated : 19 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

ArrayList is a powerful feature of C# language. It is the non-generic type of collection which is defined in System.Collections namespace. It is used to create a dynamic array means the size of the array is increase or decrease automatically according to the requirement of your program, there is no need to specify the size of the ArrayList. Or in other words, ArrayList represents an ordered collection of an object that can be indexed individually. In ArrayList, you can store elements of the same type and of the different types. It belongs to the non-generic collection. The below diagram illustrates the ArrayList class hierarchy:
 

Important Points:
 

  • The ArrayList class implements the IEnumerable, ICollection, IList, and ICloneable interfaces.
  • The ArrayList class inherits the Object class.
  • The ArrayList is defined under System.Collections namespace. So, when you use Arraylist in your program you must add System.Collections namespace.
  • You cannot implement a multi-dimensional array using ArrayList.
  • The capacity of an ArrayList is the number of elements the ArrayList can hold.
  • You are allowed to use duplicate elements in your ArrayList.
  • You can apply searching and sorting on the elements present in the ArrayList.
  • Arraylist can accept null as a valid value.

 

How to create the ArrayList?

ArrayList class has three constructors which are used to create the ArrayList.
 

  • ArrayList(): This constructor is used to create an instance of ArrayList class which is empty and having no initial capacity.
  • ArrayList(Int32): This constructor is used to create an instance of ArrayList class which is empty and having the specified initial capacity.
  • ArrayList(ICollection): This constructor is used to create an array list initialized with the elements from the specified collection and having the same initial capacity which is copied from collection.

Let’s see how to create an ArrayList using ArrayList() constructor:
 

  • Step 1: Include System.Collections namespace in your program with the help of using keyword.
    Syntax: 
     
using System.Collections;
  • Step 2: Create an ArrayList using ArrayList class as shown below:
     
ArrayList list_name = new ArrayList();
  • Step 3: If you want to add elements in your ArrayList then use Add() method to add elements in your ArrayList. As shown in the below example.
  • Step 4: The elements of the ArrayList is accessed by using a foreach loop, or by for loop, or by indexer. As shown in the below example we access the ArrayList using a foreach loop.

Example: Below program show how to create an ArrayList, adding elements to the ArrayList, and how to access the elements of the ArrayList.
 

CSharp




// C# program to demonstrate the ArrayList
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Creating ArrayList
        ArrayList My_array = new ArrayList();
 
        // Adding elements in the
        // My_array ArrayList
        // This ArrayList contains elements
        // of different types
        My_array.Add(12.56);
        My_array.Add("GeeksforGeeks");
        My_array.Add(null);
        My_array.Add('G');
        My_array.Add(1234);
 
        // Accessing the elements
        // of My_array ArrayList
        // Using foreach loop
        foreach(var elements in My_array)
        {
            Console.WriteLine(elements);
        }
    }
}


Output: 

12.56
GeeksforGeeks

G
1234

 

How to find the Capacity and Count of elements of the ArrayList?

To find this we can use Count and Capacity property of an ArrayList class as follows:
Example:
 

csharp




// C# program to find the number of
// elements and capacity of ArrayList
using System;
using System.Collections;
 
class GFG {
     
// Driver code
public static void Main() {
     
    // Creating an ArrayList
    ArrayList myList = new ArrayList();
     
    // Adding elements to ArrayList
    myList.Add(1);
    myList.Add(2);
    myList.Add(3);
    myList.Add(4);
    myList.Add(5);
     
    // Displaying count of elements of ArrayList
    Console.WriteLine("Number of elements: " + myList.Count);
     
    // Displaying Current capacity of ArrayList
    Console.WriteLine("Current capacity: " + myList.Capacity);
}
}


Output: 

Number of elements: 5
Current capacity: 8

 

How to remove elements from the ArrayList?

In ArrayList, you are allowed to remove elements from the ArrayList. ArrayList provides four different methods to remove elements and the methods are:
 

  • Remove: This method is used to remove the first occurrence of a specific object from the ArrayList.
  • RemoveAt: This method is used to remove the element at the specified index of the ArrayList.
  • RemoveRange: This method is used to remove a range of elements from the ArrayList.
  • Clear: This method is used to remove all the elements from the ArrayList.

Example:
 

CSharp




// C# program to illustrate how
// to remove elements from the
// ArrayList
using System;
using System.Collections;
 
class GFG {
 
    static public void Main()
    {
 
        // Creating ArrayList
        ArrayList My_array = new ArrayList();
 
        // Adding elements in the
        // My_array ArrayList
        // This ArrayList contains elements
        // of the same types
        My_array.Add('G');
        My_array.Add('E');
        My_array.Add('E');
        My_array.Add('K');
        My_array.Add('S');
        My_array.Add('F');
        My_array.Add('O');
        My_array.Add('R');
        My_array.Add('G');
        My_array.Add('E');
        My_array.Add('E');
        My_array.Add('K');
        My_array.Add('S');
 
        Console.WriteLine("Initial number of elements : "
                                       + My_array.Count);
 
        // Remove the 'G' element
        // from the ArrayList
        // Using Remove() method
        My_array.Remove('G');
        Console.WriteLine("After Remove() method the "+
              "number of elements: " + My_array.Count);
 
        // Remove the element present at index 8
        // Using RemoveAt() method
        My_array.RemoveAt(8);
        Console.WriteLine("After RemoveAt() method the "+
                "number of elements: " + My_array.Count);
 
        // Remove 3 elements starting from index 1
        // using RemoveRange() method
        My_array.RemoveRange(1, 3);
        Console.WriteLine("After RemoveRange() method the"+
                 " number of elements: " + My_array.Count);
 
        // Remove the all element
        // present in ArrayList
        // Using Clear() method
        My_array.Clear();
        Console.WriteLine("After Clear() method the "+
            "number of elements: " + My_array.Count);
    }
}


Output: 

Initial number of elements : 13
After Remove() method the number of elements: 12
After RemoveAt() method the number of elements: 11
After RemoveRange() method the number of elements: 8
After Clear() method the number of elements: 0

 

How to sort the elements of the ArrayList?

In ArrayList, you can perform sorting on the elements present in the given ArrayList using the Sort() method. This method uses the QuickSort algorithm to perform sorting on the ArrayList and the elements are arranged in ascending order. The use of this method is shown in the below example. 
Example:
 

CSharp




// C# program to illustrate
// sorting of ArrayList
using System;
using System.Collections;
 
public class GFG {
    static public void Main()
    {
 
        // Creating ArrayList
        ArrayList My_array = new ArrayList();
 
        // Adding elements in the
        // My_array ArrayList
        // This ArrayList contains
        // elements of the same types
        My_array.Add(1);
        My_array.Add(6);
        My_array.Add(40);
        My_array.Add(10);
        My_array.Add(5);
        My_array.Add(3);
        My_array.Add(2);
        My_array.Add(4);
 
        // ArrayList before sorting
        Console.WriteLine("ArrayList before using Sort() method:");
 
        foreach(var elements in My_array)
        {
            Console.WriteLine(elements);
        }
 
        // Sort the elements of the ArrayList
        // Using sort() method
        My_array.Sort();
 
        // ArrayList after sorting
        Console.WriteLine("ArrayList after using Sort() method:");
        foreach(var elements in My_array)
        {
            Console.WriteLine(elements);
        }
    }
}


Output: 

ArrayList before using Sort() method:
1
6
40
10
5
3
2
4
ArrayList after using Sort() method:
1
2
3
4
5
6
10
40

 

Note: 
 

  • You can also create the object of ArrayList class using the IEnumerable, ICollection, and IList interfaces but some methods of ArrayList class will not be applicable on them as they are not the members of these interfaces.
    Example:
     
// using IList Interface
IList arrlist1 = new ArrayList();

// using ICollection Interface
ICollection arrlist2 = new ArrayList();

// using IEnumerable Interface
IEnumerable arrlist3 = new ArrayList();
  • But here, you cannot apply the methods like Reverse(), AddRange() etc.
  • To read more about the constructors, properties, and methods of ArrayList class please refer to ArrayList Class.
  • To read about the difference between Array and ArrayList please refer Array vs ArrayList in C#.


Previous Article
Next Article

Similar Reads

C# | Remove the first occurrence of a specific object from the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Remove(Object) method is used to remove the first occurrence of a specific object from the ArrayList. Properties: E
3 min read
C# | Get the number of elements actually contained in the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Count property gets the number of elements actually contained in the ArrayList. Properties of ArrayList Class: Elem
3 min read
C# | Check whether an element is contained in the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Contains(Object) method determines whether the element exists in ArrayList or not. Properties of ArrayList Class: E
3 min read
C# | Check if the ArrayList is read-only
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.IsReadOnly property is used to check whether the ArrayList is read-only or not. Properties: Elements can be added o
2 min read
C# | Insert an element into the ArrayList at the specified index
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Insert(Int32, Object) method inserts an element into the ArrayList at the specified index. Properties of ArrayList
3 min read
C# | Add an object to the end of the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Add(Object) method adds an object to the end of the ArrayList. Properties of ArrayList Class: Elements can be added
2 min read
C# | Copying the elements of ArrayList to a new array
ArrayList.ToArray Method is used to copy the elements of the ArrayList to a new array. This method contains two methods in its overload list as follows: ToArray()ToArray(Type)ToArray() This method is used to copy the elements of the ArrayList to a new Object array. The elements are copied using Array.Copy, which is an O(n) operation, where n is Cou
2 min read
C# | Get or set the number of elements that the ArrayList can contain
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Capacity property is used to get or set the number of elements that the ArrayList can contain. Properties of ArrayL
2 min read
C# | Remove a range of elements from the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveRange(Int32, Int32) method is used to remove a range of elements from the ArrayList. Properties of the ArrayL
3 min read
C# | Check if the ArrayList has a fixed size
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.IsFixedSize property is used to check whether the ArrayList has a fixed size or not. Properties: Elements can be ad
2 min read
C# | Remove all elements from the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Clear method is used to remove all the elements from the ArrayList. Properties: Elements can be added or removed fr
3 min read
C# | Remove the element at the specified index of the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveAt(Int32) method is used to remove the element at the specified index of the ArrayList. Properties: Elements
3 min read
C# | Reverse the order of the elements in the entire ArrayList or in the specified range
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Reverse Method is used to reverse the order of the elements in the ArrayList in the specified range. There are two
4 min read
C# | ArrayList Class
.arraylist-table { border-collapse: collapse; width: 100%; } .arraylist-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .arraylist-table th { border: 1px solid #5fb962; padding: 8px; } .arraylist-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .arraylist-table tr:nth-child(odd) { background-color
7 min read
C# | ArrayList whose elements are copies of the specified value
ArrayList.Repeat(Object, Int32) Method is used to return an ArrayList whose elements are copies of the specified value. Or in other words, this method is used when you want to repeat a specified element in the ArrayList. This method is an O(n) operation, where n is the number of times item should be copied. Syntax: public static ArrayList Repeat (o
2 min read
C# | Copy the elements of collection over a range of elements in ArrayList
ArrayList.SetRange(Int32, ICollection) Method is used to copy the elements of a collection over a range of elements in the ArrayList. Syntax: public virtual void SetRange (int index, System.Collections.ICollection c); Parameters: index: It is a zero-based ArrayList index at which to start copying the elements of c. The type of this parameter is Sys
3 min read
C# | Sort the elements in the ArrayList
ArrayList.Sort Method is used to sorts the elements in the ArrayList. There are total 3 methods in the overload list of this method as follows: Sort()Sort(IComparer)Sort(Int32, Int32, IComparer)Sort() This method is used to Sort the elements in the entire ArrayList. It uses the QuickSort algorithm to sort the elements of the ArrayList. Note: This m
4 min read
C# | Sets the capacity to the actual number of elements in the ArrayList
ArrayList.TrimToSize Method is used to set the capacity to the actual number of elements in the ArrayList. It can be used to minimize a collection's memory overhead if no new elements will be added to the collection. Note: This method is an O(n) operation, where n is Count. Syntax: public virtual void TrimToSize (); Exception: This method will give
3 min read
C# | Adding elements to the end of the ArrayList
AddRange(ICollection) Method is used to add the elements of an ICollection to the end of the ArrayList. Or in other words, this method is used to add the multiple elements from other collection into an ArrayList. Here elements are defined as the primitive or non-primitive type. Syntax: public virtual void AddRange (ICollection col); Here, col is an
3 min read
C# | Creating a read-only wrapper for the ArrayList
ArrayList.ReadOnly(ArrayList) Method is used to get a read-only ArrayList wrapper. Syntax: public static System.Collections.ArrayList ReadOnly(System.Collections.ArrayList list); Here, the list is the ArrayList which is to be wrapped. Return Value: It returns a read-only ArrayList Wrapper around the list. Exception: This method returns the Argument
2 min read
C# | Array vs ArrayList
Arrays: An array is a group of like-typed variables that are referred to by a common name. Example: C/C++ Code // C# program to demonstrate the Arrays using System; class GFG { // Main Method public static void Main(string[] args) { // creating array int[] arr = new int[4]; // initializing array arr[0] = 47; arr[1] = 77; arr[2] = 87; arr[3] = 97; /
2 min read
C# | How to convert an ArrayList to Array
In C#, an array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float etc. and the elements are stored in a contiguous location.ArrayList represents an ordered collection of an object that can be
4 min read
C# | Check if ArrayList is Synchronized (thread safe)
ArrayList.IsSynchronized Property is used to get a value which indicate whether access to the ArrayList is synchronized (thread safe). Syntax: public virtual bool IsSynchronized { get; } Return Value: This property returns the true if access to the ArrayList is synchronized (thread safe) otherwise it returns false. The default is false. Below progr
2 min read
C# | Getting an enumerator for a range of elements in the ArrayList
ArrayList.GetEnumerator(Int32, Int32) method is used to get an enumerator for a range of elements in the ArrayList. Syntax: public virtual System.Collections.IEnumerator GetEnumerator (int index, int count); Parameters: index: It is the zero-based starting index of type Int32 of the ArrayList section that the enumerator should refer to. count: It i
3 min read
C# | Getting an enumerator for the entire ArrayList
ArrayList.GetEnumerator Method is used to get an enumerator for the entire ArrayList. Syntax: public virtual System.Collections.IEnumerator GetEnumerator (); Return Value: It returns an IEnumerator for the entire ArrayList. Below programs illustrate the use of above-discussed method: Example 1: // C# code to get an enumerator // for the entire Arra
2 min read
C# | Adding the elements to the end of the ArrayList
ArrayList.AddRange(ICollection) Method is used to add the elements of an ICollection to the end of the ArrayList. Syntax: public virtual void AddRange (System.Collections.ICollection c); Here, c is the ICollection whose elements should be added to the end of the ArrayList. The collection itself cannot be null, but it can contain elements that are n
2 min read
C# | Get or set the element at the specified index in ArrayList
ArrayList.Item[Int32] Property is used to get or set the element at the specified index in ArrayList. Syntax: public virtual object this[int index] { get; set; } Here, index is the zero-based index of the element to get or set. Return Value: It returns the element of Object type at the specified index. Exception: This property will throw ArgumentOu
2 min read
C# | Creating a synchronized (thread-safe) wrapper for the ArrayList
Synchronized(ArrayList) method is used to get an ArrayList wrapper that is synchronized (thread safe). Syntax: public static System.Collections.ArrayList Synchronized (System.Collections.ArrayList list); Here, the list is the ArrayList which is to be synchronized. Return Value: It returns an ArrayList wrapper which is synchronized (thread safe). Ex
2 min read
C# | Getting a subset of the elements from the source ArrayList
ArrayList.GetRange(Int32, Int32) Method is used to get an ArrayList which will represent a subset of the elements in the source ArrayList. Syntax: public virtual System.Collections.ArrayList GetRange (int index, int count); Parameters: index: It is of Int32 type and represents the zero-based ArrayList index at which the range starts. count: It is o
3 min read
C# | How to copy the entire ArrayList to a one-dimensional Array
ArrayList.CopyTo Method is used to copy the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array. Syntax: public virtual void CopyTo (Array array); Here, array is the one-dimensional Array which is the destination of the elements copied from ArrayList. The Array must have zero-based indexing. Excepti
3 min read