What is the Capacity property of an ArrayList class in C#?

CsharpProgrammingServer Side Programming

The capacity property in ArrayList class gets or sets the number of elements that the ArrayList can contain.

Capacity is always greater than count. For capacity property −

arrList.Capacity

The default capacity is 4. If 5 elements are there, then its capacity is doubled and would be 8. This goes on.

You can try to run the following the code to implement Capacity property in C#. This also shows what we discussed above −

Example

 Live Demo

using System;
using System.Collections;

class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add(19);
      arrList.Add(44);
      arrList.Add(22);

      ArrayList arrList2 = new ArrayList();
      arrList2.Add(19);
      arrList2.Add(44);
      arrList2.Add(64);
      arrList2.Add(32);
      arrList2.Add(99);

      Console.WriteLine("ArrayList1 - Total elements: "+arrList.Count);
      Console.WriteLine("ArrayList1 - Capacity: "+arrList.Capacity);

      Console.WriteLine("ArrayList2 - Total elements: "+arrList2.Count);
      Console.WriteLine("ArrayList2 - Capacity: "+arrList2.Capacity);
     
   }
}

Output

ArrayList1 - Total elements: 3
ArrayList1 - Capacity: 4
ArrayList2 - Total elements: 5
ArrayList2 - Capacity: 8
raja
Published on 07-Aug-2018 07:59:37
Advertisements