Open In App

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 ArrayList Class:



Syntax:

public virtual int Capacity { get; set; }

Return Value: The number of elements that the ArrayList can contain.



Exceptions:

Example:




// C# code to get or set the number 
// of elements that the ArrayList can contain
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

Important Points:

Reference:

Article Tags :
C#