Skip to content

#16.1 ArrayList

It can contain/hold elements of any data types. Unlike an array, you needn’t have to declare the size as it increases dynamically.

Derived from: IEnumerator -> IEnumberable -> ICollection -> IList

Important Properties of ArrayList:

PropertiesDescription
CapacityGets or sets the number of elements that the ArrayList can contain
CountGets the number of elements actually contained in the ArrayList
IsFixedSizeGets the value indicating whether the ArrayList has a fixed size.
isReadOnlyGets a value indicating whether the ArrayList is read-only.
ItemGets or sets the element at the specific index.
MethodDescription
Add() / AddRange()Add an element / Add collection or group of elements to the ArrayList.
Insert() / InsertRange()Insert an element at a specific index/insert collection starting from a specific index.
Remove / RemoveRange()Remove an element at a specific index/remove range of elements.
RemoveAt()Remove at a specific index.
ContainsChecks whether a specified element exists in the ArrayList or not. Returns true if exists otherwise false.
ClearRemoves all the elements in ArrayList.
ToArrayReturns a compatible array from an ArrayList.
using System;
using System.Collections;

namespace ArraylistApplication
{   
    public class Program
    {
        static void Main(string[] args)
        {
            ArrayList Arr = new ArrayList(); //Array List declaration

            ArrayList A1 = new ArrayList() { 1, 2, 3, 4, 5 };

            Arr.Add(1); //Adding elements to the arraylist object
            Arr.Add("string");
            Arr.Add(4.5);
            Arr.Insert(2, "insered using insert method");
            Arr.AddRange(A1); //Adding an collection to an array

            int[] array = new int[] { 7, 8, 9 };

            Arr.AddRange(array); //Adding an array to the arraylist

            for (int i = 0; i < Arr.Count; i++)
            {
                Console.WriteLine("{0}  index {1}",Arr[i], i);
            }

            Arr.Remove("string"); //remove the word string
            Console.WriteLine();
            Console.WriteLine("After remove");
            foreach (var item in Arr)
            {
                Console.WriteLine(item);
            }

            Arr.RemoveAt(1); //remove element with index 1
            Console.WriteLine();
            Console.WriteLine("After removeat");
            foreach (var item in Arr)
            {
                Console.WriteLine(item);
            }

            Arr.RemoveRange(0, 3); //remove 3 elements from index 0
            Console.WriteLine();
            Console.WriteLine("After remove range");
            foreach (var item in Arr)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}
Published inC#

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *