C# Dynamic Arrays (ArrayList)
ArrayList is a dynamic array class provided in C#, located in the System.Collections namespace.
Unlike ordinary arrays, a dynamic array (ArrayList) can have its size adjusted dynamically, without the need to predefine a fixed length.
A dynamic array (ArrayList) represents an ordered collection of objects that can be individually indexed; it also allows dynamic memory allocation, addition, searching, and sorting of items in the list.
ArrayList The class is suitable for array operations that require frequent resizing, but due to its non-generic nature, it is gradually being replaced by List as a replacement.
Basic structure
public class ArrayList : ICollection, IEnumerable, IList, ICloneable
Implemented interfaces:
- Implementing an interface:
IList: supports accessing elements by index.ICollection: supports basic collection operations such as adding, removing, and counting.IEnumerable: supports iterating over elements through an enumerator.ICloneable: supports cloningArrayList。
Feature
Dynamic Scaling:
ArrayListIts capacity can be adjusted automatically as needed, without specifying a fixed size.- When the added elements exceed the current capacity,
ArrayListthe capacity is increased automatically (usually doubling the original capacity).
Non-generic collection:
ArrayListis a non-generic collection; all elements are stored asobjecttype. This means it can store objects of any type, but attention must be paid to the performance impact of boxing and unboxing.
Unsorted operations:
- Although the storage order of elements is consistent with the order of addition, it does not provide built-in sorting functionality.
Thread Safety:
- It is not thread-safe by default. If you need a thread-safe
ArrayListinstalled, you can useArrayList.Synchronizedmethod to generate a thread-safe version.
Methods and properties of the ArrayList class
The following table lists the ArrayList Some commonly used members of the class property:
| Attribute name | Type | Description |
|---|---|---|
Count |
int |
Obtain the ArrayList the number of elements contained in ArrayList. |
Capacity |
int |
Gets or sets the ArrayList capacity (storage space) of ArrayList. |
IsFixedSize |
bool |
Indicates whether ArrayList ArrayList has a fixed size. |
IsReadOnly |
bool |
Indicates whether ArrayList whether it is read-only. |
IsSynchronized |
bool |
Indicates whether ArrayList whether it is thread-safe. |
SyncRoot |
object |
Gets the object that can be used to synchronize access. |
The following table lists the ArrayList Some commonly used members of the class Method:
| Method Name | Return Type | Description |
|---|---|---|
| Adding and inserting | ||
Add(object value) |
int |
Adds an object to the ArrayList end of ArrayList, returning the index of the new element. |
AddRange(ICollection c) |
void |
Adds all elements of the specified collection to the ArrayList end of the |
Insert(int index, object value) |
void |
Inserts an object at the specified index. |
InsertRange(int index, ICollection c) |
void |
Inserts all elements of the specified collection at the specified index. |
| Delete | ||
Remove(object value) |
void |
Removes the first occurrence of the specified object. |
RemoveAt(int index) |
void |
Removes the element at the specified index. |
RemoveRange(int index, int count) |
void |
Removes the specified number of elements starting from the specified index. |
Clear() |
void |
Removes all elements. |
| Access and query | ||
Contains(object item) |
bool |
Decision ArrayList Whether it contains the specified object. |
IndexOf(object value) |
int |
Gets the index of the first occurrence of the specified object. |
LastIndexOf(object value) |
int |
Gets the index of the last occurrence of the specified object. |
| Sorting and copying | ||
Sort() |
void |
Sorts according to the default order ArrayList elements in . |
Sort(IComparer comparer) |
void |
Sorts according to a custom comparer. |
Reverse() |
void |
Reverse ArrayList the order of the elements in ArrayList. |
CopyTo(Array array) |
void |
data to the child component via ArrayList the elements of ArrayList to the specified array. |
| Others | ||
GetRange(int index, int count) |
ArrayList |
Gets a subset of the specified number of elements starting from the specified index. |
ToArray() |
object[] |
data to the child component via ArrayList the elements in ArrayList to an array. |
TrimToSize() |
void |
Adjusts the capacity to the actual number of elements to save memory. |
Example
The following example demonstrates the concept of a dynamic array (ArrayList):
Example
using
System
;
using
System.Collections
;
namespace
CollectionApplication
{
class
Program
{
static
void
Main
(
string
[
]
args
)
{
// Create and initialize a dynamic array
ArrayList numbers
=
InitializeArrayList
(
)
;
// Display the capacity and element count of the array
DisplayArrayListInfo
(
numbers
)
;
// Display the contents of the array
Console
.
Write
(
"Original Content: "
)
;
DisplayArrayListContent
(
numbers
)
;
// Sort the contents of the array
numbers
.
Sort
(
)
;
// Display the sorted contents
Console
.
Write
(
"Sorted Content: "
)
;
DisplayArrayListContent
(
numbers
)
;
Console
.
ReadKey
(
)
;
// Wait for the user to press a key to exit
}
///
/// Initialize and populate the ArrayList
///
///
static
ArrayList InitializeArrayList
(
)
{
ArrayList al
=
new
ArrayList
(
)
;
Console
.
WriteLine
(
"Adding numbers to the ArrayList:"
)
;
// Add initial elements
int
[
]
initialNumbers
=
{
45
,
78
,
33
,
56
,
12
,
23
,
9
}
;
foreach
(
int
num
in
initialNumbers
)
{
al
.
Add
(
num
)
;
Console
.
WriteLine
(
$
"Added: {num}"
)
;
}
return
al
;
}
///
/// Display the capacity and element count of the ArrayList
///
/// ArrayList object
static
void
DisplayArrayListInfo
(
ArrayList al
)
{
Console
.
WriteLine
(
$
"\nCapacity: {al.Capacity}"
)
;
// Current capacity
Console
.
WriteLine
(
$
"Count: {al.Count}"
)
;
// Current element count
}
///
/// Display the contents of the ArrayList
///
/// ArrayList object
static
void
DisplayArrayListContent
(
ArrayList al
)
{
foreach
(
int
num
in
al
)
{
Console
.
Write
(
num
" "
)
;
}
Console
.
WriteLine
(
)
;
// Newline
}
}
}
When the code above is compiled and executed, it produces the following result:
Adding numbers to the ArrayList:
Added: 45
Added: 78
Added: 33
Added: 56
Added: 12
Added: 23
Added: 9
Capacity: 16
Count: 7
Original Content: 45 78 33 56 12 23 9
Sorted Content: 9 12 23 33 45 56 78
Compared with generic List collections
| Feature | ArrayList |
List |
|---|---|---|
| Type Safety | No (stores object type) |
Yes (generic, strongly typed constraints) |
| Boxing and unboxing | Yes (required for value types) | No |
| Performance | Lower | Higher |
| Generic Support | None | Yes |
| Use Cases | Legacy code or simple scenarios | Preferred in modern development |
Notes
Avoid frequent boxing and unboxing:
- If the data is mainly value types, it is recommended to use
Listto avoid performance overhead.
Use mixed-type data with caution:
- Try not to store objects of different types mixed together, to reduce the risk of runtime errors.
Alternatives:
- In modern C# development, generic collections (such as
List、Dictionary) are recommended to improve code safety and efficiency.
C# Collections