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 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
                };

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.

Comments

Popular posts from this blog

C# | Association, Aggregation and Composition

Throw vs Throw ex in C#

C# Extension Method