An Arraylist is a collection which can store any item of type object. The number of objects can dynamically increase or decrease.
Important features of C# Arraylist class
Below are some of the important features of an Arraylist class.
- Arraylist is a weakly typed collection object.
- Arraylist may or may not be sorted by default.
- It can store billions of elements.
- To access an item in an Arraylist indexes are used.
- It allows null values.
- It allows duplicate elements.
- Performance wise Arraylist is slower compared to generic List.
Create a C# Arraylist object
An Arraylist can be created by using the below code.
ArrayList list = new ArrayList();
Add and remove items from C# Arraylist
When writing programs using Arraylist two most common operations performed are adding and removing items.
list.Add("Hello"); list.Remove("Hello");
For Loop to access items in C# Arraylist
To display items stored in an Arraylist a loop can be used.
ArrayList list = new ArrayList(); list.Add("Hello"); list.Add("Universe"); for (int count = 0; count < list.Count; count++) { Console.WriteLine(list[count]); }
Output:
Hello
Universe
Hello
Universe
Methods and Properties of a C# Arraylist
Commonly used methods of an Arraylist are:
Method | Description |
---|---|
Add | Adds an item at the end of an Arraylist. |
AddRange | Adds the elements of an collection to the end of an Arraylist. |
Clear | Removes all the elements from an Arraylist. |
Contains | Checks if an item is present in an Arraylist. |
IndexOf(Object) | Determines the position of an object and returns the zero-based index of that object in an Arraylist. |
Insert | Inserts an item in an Arraylist at a specified index. |
InsertRange | Inserts the elements of an collection at a specific index of an Arraylist. |
Remove | Searches for an item and removes the first occurrence of that item from an Arraylist. |
RemoveAt | Removes an item from an Arraylist at a specific index. |
RemoveRange | Removes a contiguous list of items from an ArrayList. |
Reverse | Reverses the order of the items present in an Arraylist. |
Sort | Sorts the items of an Arraylist. |
Commonly used properties of an Arraylist are:
Property | Description |
---|---|
Count | Returns the number of items present in an Arraylist. |
IsReadOnly | Returns a boolean value which specifies whether an Arraylist is read-only or not. |
Item | This property is used along with an index to get or set a value. |