YouTip LogoYouTip

Csharp Arraylist

[![Image 1: C# Collections](#) C# Collections](#) ArrayList is a dynamic array class provided in C#, located in the `System.Collections` namespace. A dynamic array (ArrayList) differs from a regular array in that its size can be adjusted dynamically, without the need to define a fixed length in advance. A dynamic array (ArrayList) represents an ordered collection of objects that can be individually indexed. It also allows for dynamic memory allocation, addition, searching, and sorting of items within the list. The `ArrayList` class is suitable for array operations that require frequent resizing, but due to its non-generic nature, it is gradually being replaced by `List` in modern C# development. ### Basic Structure ```csharp public class ArrayList : ICollection, IEnumerable, IList, ICloneable **Implemented Interfaces:** * **Implemented Interfaces**: * `IList`: Supports accessing elements by index. * `ICollection`: Supports basic collection operations like adding, removing, and counting. * `IEnumerable`: Supports iterating over elements using an enumerator. * `ICloneable`: Supports cloning the `ArrayList`. ### Characteristics **Dynamic Expansion**: * The capacity of an `ArrayList` can automatically adjust as needed, without specifying a fixed size. * When the number of added elements exceeds the current capacity, the `ArrayList` automatically increases its capacity (typically doubling the original capacity). **Non-Generic Collection**: * `ArrayList` is a non-generic collection, meaning all elements are stored as `object` type. This allows it to store objects of any type, but be mindful of the performance impact of boxing and unboxing. **Unordered Operations**: * Although the storage order of elements matches the order in which they are added, it does not provide built-in sorting functionality. **Thread Safety**: * By default, it is not thread-safe. If a thread-safe `ArrayList` is needed, you can use the `ArrayList.Synchronized` method to generate a thread-safe version. The following table lists some common **properties** of the **ArrayList** class: | Property Name | Type | Description | | --- | --- | --- | | `Count` | `int` | Gets the number of elements contained in the `ArrayList`. | | `Capacity` | `int` | Gets or sets the capacity (storage space) of the `ArrayList`. | | `IsFixedSize` | `bool` | Indicates whether the `ArrayList` has a fixed size. | | `IsReadOnly` | `bool` | Indicates whether the `ArrayList` is read-only. | | `IsSynchronized` | `bool` | Indicates whether the `ArrayList` is thread-safe. | | `SyncRoot` | `object` | Gets an object that can be used to synchronize access to the `ArrayList`. | The following table lists some common **methods** of the **ArrayList** class: | Method Name | Return Type | Description | | --- | --- | --- | | **Adding and Inserting** | | | | `Add(object value)` | `int` | Adds an object to the end of the `ArrayList`, returning the index of the new element. | | `AddRange(ICollection c)` | `void` | Adds all elements from the specified collection to the end of the `ArrayList`. | | `Insert(int index, object value)` | `void` | Inserts an object at the specified index. | | `InsertRange(int index, ICollection c)` | `void` | Inserts all elements from the specified collection at the specified index. | | **Removing** | | | | `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 a range of elements starting from the specified index. | | `Clear()` | `void` | Removes all elements from the `ArrayList`. | | **Accessing and Querying** | | | | `Contains(object item)` | `bool` | Determines whether the `ArrayList` contains a specific object. | | `IndexOf(object value)` | `int` | Returns the index of the first occurrence of the specified object. | | `LastIndexOf(object value)` | `int` | Returns the index of the last occurrence of the specified object. | | **Sorting and Copying** | | | | `Sort()` | `void` | Sorts the elements in the `ArrayList` using the default comparer. | | `Sort(IComparer comparer)` | `void` | Sorts the elements using a custom comparer. | | `Reverse()` | `void` | Reverses the order of elements in the `ArrayList`. | | `CopyTo(Array array)` | `void` | Copies the elements of the `ArrayList` to a specified array. | | **Other** | | | | `GetRange(int index, int count)` | `ArrayList` | Returns a subset of elements starting from the specified index. | | `ToArray()` | `object[]` | Copies the elements of the `ArrayList` to a new array. | | `TrimToSize()` | `void` | Sets the capacity to the actual number of elements to save memory. | The following example demonstrates the concept of a dynamic array (ArrayList): ## Example ```csharp using System; using System.Collections; namespace CollectionApplication { class Program { static void Main(string[] args) { // Create dynamic array and initialize. ArrayList numbers = InitializeArrayList(); // Display array's capacity and element count. DisplayArrayListInfo(numbers); // Display array content. Console.Write("Original Content: "); DisplayArrayListContent(numbers); // Sort the array content. numbers.Sort(); // Display sorted content. Console.Write("Sorted Content: "); DisplayArrayListContent(numbers); Console.ReadKey(); // Wait for user to press key to exit. } /// /// Initialize and fill ArrayList. /// /// ArrayList containing initial data. 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 ArrayList's capacity and element count. /// /// ArrayList Objects static void DisplayArrayListInfo(ArrayList al) { Console.WriteLine($"nCapacity: {al.Capacity}"); // Current capacity. Console.WriteLine($"Count: {al.Count}"); // Current element count. } /// /// Display the content of ArrayList. /// /// ArrayList Objects static void DisplayArrayListContent(ArrayList al) { foreach (int num in al) { Console.Write(num + " "); } Console.WriteLine(); // Line break. } } } When the above code 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 ### **Comparison with Generic Collection `List`** | Feature | `ArrayList` | `List` | | --- | --- | --- | | Type Safety | No (stores `object` type) | Yes (generic, strongly typed constraint) | | Boxing/Unboxing | Yes (required for value types) | No | | Performance | Lower | Higher | | Generic Support | No | Yes | | Use Case | Legacy code or simple scenarios | Preferred in modern development | ### Important Notes **Avoid Frequent Boxing and Unboxing**: * If your data consists mainly of value types, it is recommended to use `List` to avoid performance overhead. **Use Caution with Mixed Type Data**: * Try to avoid storing objects of different types together to reduce the risk of runtime errors. **Alternative Solutions**: * In modern C# development, it is recommended to use generic collections (such as `List`, `Dictionary`) to improve code safety and efficiency. [![Image 2: C# Collections](#) C# Collections](#)
← Csharp HashtableCsharp Collection β†’