C# Arraylist Examples – C# Programming Example
Arrays C# Console Foreach Statement

C# Arraylist Examples

It represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array.

For arrays, you need to define the number of elements that the array can hold at the time of array declaration. But in the case of the Array List collection, this does not need to be done beforehand. Elements can be added or removed from the Array List collection at any point in time. Let’s look at the operations available for the array list collection in more detail.

Properties of ArrayList Class

Capacity : Gets or sets the number of elements that the ArrayList can contain.

Count : Gets the number of elements actually contained in the ArrayList.

IsFixedSize : Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly : Gets a value indicating whether the ArrayList is read-only.

Item : Gets or sets the element at the specified index.

 

Methods of ArrayList Class

Add: Adds an object to the end of the ArrayList.

AddRange: Adds the elements of an ICollection to the end of the ArrayList.

Clear: Removes all elements from the ArrayList.

Contains: Determines whether an element is in the ArrayList.

GetRange: Returns an ArrayList which represents a subset of the elements in the source ArrayList.

IndexOf: Returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it.

Insert: Inserts an element into the ArrayList at the specified index.

InsertRange: Inserts the elements of a collection into the ArrayList at the specified index.

Remove: Removes the first occurrence of a specific object from the ArrayList.

RemoveAt: Removes the element at the specified index of the ArrayList.

RemoveRange: Removes a range of elements from the ArrayList.

Reverse: Reverses the order of the elements in the ArrayList.

SetRange: Copies the elements of a collection over a range of elements in the ArrayList.

Sort: Sorts the elements in the ArrayList.

TrimToSize: Sets the capacity to the actual number of elements in the ArrayList.

Declaration of an Array List

The declaration of an ArrayList is provided below. An array list is created with the help of the ArrayList Data type. The “new” keyword is used to create an object of an ArrayList.

Adding elements to an ArrayList

Display the elements of the ArrayList.

Output:

Print an ArrayList with a for-each loop

Output:

csharp
console
examples

 

Count:

Output: 

3

 

Contains:

Output:

false

 

RemoveAt:

Output:

csharp
examples

 

Sort:

Output:

console
csharp
examples

 

Reverse:

Output:

examples
console
csharp

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: