Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

C# - ArrayList

In C#, the ArrayList is a non-generic collection of objects whose size increases dynamically. It is the same as Array except that its size increases dynamically.

An ArrayList can be used to add unknown data where you don't know the types and the size of the data.

Create an ArrayList

The ArrayList class included in the System.Collections namespace. Create an object of the ArrayList using the new keyword.

Example: Create an ArrayList
using System.Collections;

ArrayList arlist = new ArrayList(); 
// or 
var arlist = new ArrayList(); // recommended

Adding Elements in ArrayList

Use the Add() method or object initializer syntax to add elements in an ArrayList.

An ArrayList can contain multiple null and duplicate values.

Example: Adding Elements in ArrayList
// adding elements using ArrayList.Add() method
var arlist1 = new ArrayList();
arlist1.Add(1);
arlist1.Add("Bill");
arlist1.Add(" ");
arlist1.Add(true);
arlist1.Add(4.5);
arlist1.Add(null);

// adding elements using object initializer syntax
var arlist2 = new ArrayList()
                {
                    2, "Steve", " ", true, 4.5, null
                };
Try it

Use the AddRange(ICollection c) method to add an entire Array, HashTable, SortedList, ArrayList, BitArray, Queue, and Stack in the ArrayList.

Example: Adding Entire Array/ArrayList into ArrayList
var arlist1 = new ArrayList();

var arlist2 = new ArrayList()
                    {
                        1, "Bill", " ", true, 4.5, null
                    };

int[] arr = { 100, 200, 300, 400 };

Queue myQ = new Queue();
myQ.Enqueue("Hello");
myQ.Enqueue("World!");

arlist1.AddRange(arlist2); //adding arraylist in arraylist 
arlist1.AddRange(arr); //adding array in arraylist 
arlist1.AddRange(myQ); //adding Queue in arraylist
Try it

Accessing an ArrayList

The ArrayList class implements the IList interface. So, elements can be accessed using indexer, in the same way as an array. Index starts from zero and increases by one for each subsequent element.

An explicit casting to the appropriate types is required, or use the var variable.

Example: Accessing Elements of ArrayList
var arlist = new ArrayList()
                {
                    1,
                    "Bill",
                    300,
                    4.5f
                };

//Access individual item using indexer
int firstElement = (int) arlist[0]; //returns 1
string secondElement = (string) arlist[1]; //returns "Bill"
//int secondElement = (int) arlist[1]; //Error: cannot cover string to int

//using var keyword without explicit casting
var firstElement = arlist[0]; //returns 1
var secondElement = arlist[1]; //returns "Bill"
//var fifthElement = arlist[5]; //Error: Index out of range

//update elements
arlist[0] = "Steve"; 
arlist[1] = 100;
//arlist[5] = 500; //Error: Index out of range
Try it

Iterate an ArrayList

The ArrayList implements the ICollection interface that supports iteration of the collection types. So, use the foreach and the for loop to iterate an ArrayList. The Count property of an ArrayList returns the total number of elements in an ArrayList.

Example: Iterate ArrayList
ArrayList arlist = new ArrayList()
                        {
                            1,
                            "Bill",
                            300,
                            4.5F
                        };

foreach (var item in arlist)
    Console.Write(item + ", "); //output: 1, Bill, 300, 4.5, 
            
for(int i = 0 ; i < arlist.Count; i++)
    Console.Write(arlist[i] + ", "); //output: 1, Bill, 300, 4.5,
Try it

Insert Elements in ArrayList

Use the Insert() method to insert an element at the specified index into an ArrayList.

Signature: void Insert(int index, Object value)

Example: Insert Element in ArrayList
ArrayList arlist = new ArrayList()
                {
                    1,
                    "Bill",
                    300,
                    4.5f
                };

arlist.Insert(1, "Second Item");

foreach (var val in arlist)
    Console.WriteLine(val);
Try it

Use the InsertRange() method to insert a collection in an ArrayList at the specfied index.

Signature: Void InsertRange(int index, ICollection c)

Example: Insert Collection in ArrayList
ArrayList arlist1 = new ArrayList()
                {
                    100, 200, 600
                };

ArrayList arlist2 = new ArrayList()
                {
                    300, 400, 500
                };
arlist1.InsertRange(2, arlist2);

foreach(var item in arlist1)
    Console.Write(item + ", "); //output: 100, 200, 300, 400, 500, 600,
Try it

Remove Elements from ArrayList

Use the Remove(), RemoveAt(), or RemoveRange methods to remove elements from an ArrayList.

Example: Remove Elements from ArrayList
ArrayList arList = new ArrayList()
                {
                    1,
                    null,
                    "Bill",
                    300,
                    " ",
                    4.5f,
                    300,
                };

arList.Remove(null); //Removes first occurance of null
arList.RemoveAt(4); //Removes element at index 4
arList.RemoveRange(0, 2);//Removes two elements starting from 1st item (0 index)
Try it

Check Element in ArrayList

Use the Contains() method to determine whether the specified element exists in the ArrayList or not. It returns true if exists otherwise returns false.

Example: Check for Elements
ArrayList arList = new ArrayList()
                {
                    1,
                    "Bill",
                    300,
                    4.5f,
                    300
                };

Console.WriteLine(arList.Contains(300)); // true
Console.WriteLine(arList.Contains("Bill")); // true
Console.WriteLine(arList.Contains(10)); // false
Console.WriteLine(arList.Contains("Steve")); // false
Try it
Note:
It is not recommended to use the ArrayList class due to performance issue. Instead, use List<object> to store heterogeneous objects. To store data of same data type, use Generic List<T>.

ArrayList Class

The following diagram illustrates the ArrayList class.

C# ArrayList

ArrayList Properties

PropertiesDescription
CapacityGets or sets the number of elements that the ArrayList can contain.
CountGets the number of elements actually contained in the ArrayList.
IsFixedSizeGets a 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 specified index.

ArrayList Methods

MethodsDescription
Add()/AddRange()Add() method adds single elements at the end of ArrayList.
AddRange() method adds all the elements from the specified collection into ArrayList.
Insert()/InsertRange()Insert() method insert a single elements at the specified index in ArrayList.
InsertRange() method insert all the elements of the specified collection starting from specified index in ArrayList.
Remove()/RemoveRange()Remove() method removes the specified element from the ArrayList.
RemoveRange() method removes a range of elements from the ArrayList.
RemoveAt()Removes the element at the specified index from the ArrayList.
Sort()Sorts entire elements of the ArrayList.
Reverse()Reverses the order of the elements in the entire ArrayList.
ContainsChecks whether specified element exists in the ArrayList or not. Returns true if exists otherwise false.
ClearRemoves all the elements in ArrayList.
CopyToCopies all the elements or range of elements to compitible Array.
GetRangeReturns specified number of elements from specified index from ArrayList.
IndexOfSearch specified element and returns zero based index if found. Returns -1 if element not found.
ToArrayReturns compitible array from an ArrayList.
Further Reading
  • Difference between Array & ArrayList
  • ArrayList's Methods & Properties
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.