ArrayList Class in C#

In this article we will discuss about the what is ArrayList Class in C# and also how it will be implemented in C#.
  • 3442

The ArrayList Class is one of the Collection Class. It is like Array in C# except that  it can collect different kind of data and its size grows dynamically  as the number of elements changes in it. Unlike the Array its size is not fix. An ArrayList uses the array internally and by default an array is declared with 4 capacity and it will increment or decrement two times like 8 as the number of element will be inserted. If we want we can change its capacity by using TrimeToSize() method available in the ArrayList Class.

The size of the ArrayList is the total number of elements that are currently present in the ArrayList itself whereas Capacity of the ArrayList is defined by the Number of element an ArrayList can hold.

The following program of ArrayList is as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

 

namespace ConsoleApplication13

{

    class Program

    {

        static void Main(string[] args)

        {

            ArrayList obj = new ArrayList();

            obj.Add("Rahul");

            obj.Add("23");

            obj.Add("Aman");

            obj.Add("Akansha");

            obj.Add("27");

            Console.WriteLine("Count is:"+obj.Count.ToString());

            Console.WriteLine("Capacity:"+obj.Capacity.ToString());

            foreach (Object o in obj)

            {

                Console.WriteLine(o.ToString());

            }

            obj.TrimToSize();

            Console.WriteLine("capacity is:"+obj.Capacity.ToString());

            Console.ReadLine();

 

        }

    }

}

Output:

image4.jpg

In the above output it is clear that there are total 5 elements we have inserted in ArrayList and the Capacity of the ArrayList is 8 and when we have used TrimToSize() method the capacity is decrease to 5 that means we know that by default ArrayList Capacity is 4 and when we insert an item in the ArrayList its Capacity increases two times i.e. 8 and only there 5 elements in the ArrayList so we are using TrimToSize() method to trim the Capacity of the ArrayList according to the number of elemnt it is containing.

Further Readings
 
You may also want to read these related articles.

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.