ArrayList in C#

Learn via video courses
Topics Covered

Overview

ArrayList is a data structure in C# that allows us to create a collection of elements of any data type. It's like a dynamic array that can grow or shrink as we add or remove elements. For example, we can have a list of integers, strings, doubles, or any other objects, all in the same ArrayList. This flexibility can be useful in certain situations, but it comes with some drawbacks.

Since ArrayList can hold elements of different types, it needs to store them as object types internally. This process is called "boxing". When we retrieve elements from the ArrayList, they need to be "unboxed" back to their original types, which can lead to some performance overhead.

Introduction to arraylist in c#

In C#, ArrayList is a class provided by the .NET Framework within the System.Collections namespace. It represents a dynamic array-like data structure that can hold elements of any data type. Unlike regular arrays in C#, which have a fixed size once they are created, ArrayList can automatically resize itself to accommodate new elements as needed.

The key features of ArrayList are as follows:

  • Dynamic Sizing: ArrayList effortlessly resizes itself as elements are added or removed, eliminating manual array resizing concerns.
  • Heterogeneous Elements: It supports different data types, though mixing types may lead to runtime errors.
  • Boxing and Unboxing: Value types are converted to objects (boxing) when added and restored (unboxing) upon retrieval, impacting performance.
  • Usage of object: Internally, ArrayList employs an object[] array to store elements, treating each added item as an object.

Example: Here's a simple example of using ArrayList

Output:

Although ArrayList can be useful in certain scenarios, it's important to note that with the introduction of generics in C# 2.0, it is generally recommended to use the more type-safe and efficient List<T> class instead of ArrayList for new code. The use of List<T> helps avoid boxing/unboxing and provides better compile-time type checking, leading to more reliable and performant code.

How to Create an ArrayList

To create an ArrayList in C#, we need to follow these steps:

Step 1: Import the System.Collections namespace

Before we can use the ArrayList class, we need to include the System.Collections namespace in your code.

Step 2: Instantiate the ArrayList

After importing the namespace, we can create an instance of the ArrayList class using the new keyword and the ArrayList constructor.

Step 3: Add Elements to the ArrayList

Once we have created the ArrayList, we can add elements to it using the Add() method. You can add elements of any data type since ArrayList supports heterogeneity.

Step 4: Access Elements from the ArrayList

We can access elements in the ArrayList using the indexer (square bracket) notation. Keep in mind that since ArrayList stores elements as objects, we need to cast them back to their original types when retrieving them.

Step 5: Iterate Through the ArrayList

We can use a foreach loop to iterate through the elements of the ArrayList.

Here's the code to create array list in C#:

Output:

Note: Remember that if we are working with C# 2.0 or later, it is recommended to use List<T> instead of ArrayList for better type safety and performance. List<T> provides a more efficient and type-safe alternative to ArrayList, as it allows us to specify the data type the list will hold, and it avoids the need for boxing and unboxing.

How to Adding Elements in ArrayList

To add elements to an ArrayList in C#, we can use the Add() method. The Add() method allows you to add elements of any data type to the ArrayList, as it supports heterogeneity. Here's how we can do it.

Example:

Output:

In the example above, we created an ArrayList named arrayList. We then used the Add() method to add elements of various data types: an integer, a string, a double, a boolean, and a character. The foreach loop is used to iterate through the elements and display them on the console.

Accessing an ArrayList

To access elements in an ArrayList in C#, we can use the indexer (square bracket) notation. Since ArrayList is an ordered collection, each element is associated with an index, starting from 0 for the first element, 1 for the second element, and so on. Here's how we can access elements from an ArrayList.

Example:

In the example above, we first created an ArrayList named arrayList and added three elements to it: an integer, a string, and a double.

Output:

How to Iterate an ArrayList

To iterate through the elements of an ArrayList in C#, we have several options. We can use a for loop, a foreach loop, or even the GetEnumerator() method. Here's how we can do it using each method.

Using a for Loop

We can use a traditional for loop with the Count property to iterate through the ArrayList elements.

Output:

Using a foreach Loop

A foreach loop is a simpler and cleaner way to iterate through the elements of the ArrayList. The loop automatically takes care of accessing each element without the need for an index.

Output:

Using GetEnumerator() Method

ArrayList implements the IEnumerable interface, which allows us to obtain an enumerator to iterate through its elements. We can use this enumerator with a while loop to access each element.

Output:

All three methods will give us the same output, displaying each element of the ArrayList on the console.

How to Insert Elements in ArrayList

To insert elements at a specific position in an ArrayList in C#, we can use the Insert() method. The Insert() method allows you to add an element at a specified index within the ArrayList. Any existing elements at or after the specified index will be shifted to accommodate the new element.

Example:

Output:

In the example above, we created an ArrayList named arrayList and added three elements to it: an integer, a string, and a double.

To insert an element at a specific index, we used the Insert() method. In this case, we inserted the value "Inserted Value" at index 1, which shifted the original string "Hello" and the double to positions 2 and 3, respectively.

The output shows that the element "Inserted Value" was inserted at index 1, and the original elements were shifted accordingly.

How to Remove Elements from ArrayList

To remove elements from an ArrayList in C#, we have several methods available, such as Remove(), RemoveAt(), and Clear(). Each method serves a different purpose for removing elements from the collection. Here's how we can use these methods.

In the example above, we created an ArrayList named arrayList and added three elements to it: an integer, a string, and a double.

To remove elements, we used the following methods:

  • Using Remove(): The Remove() method allows you to remove a specific element from the ArrayList. It takes the element you want to remove as an argument.
  • Using RemoveAt(): TheRemoveAt()method allows you to remove an element at a specific index in the ArrayList. It takes the index of the element you want to remove as an argument.
  • Using Clear(): The Clear() method removes all elements from the ArrayList, effectively emptying the list.

Example:

Output:

Note: When using Remove() and RemoveAt(), the ArrayList will modify itself by shifting the remaining elements to fill the removed element's position.

How to Check Element in ArrayList

To check if an element exists in an ArrayList in C#, we can use the Contains() method or the IndexOf() method.

  • Using Contains(): The Contains() method checks if the specified element exists in the ArrayList. It returns true if the element is found and false otherwise.
  • Using IndexOf(): The IndexOf() method returns the index of the first occurrence of the specified element in the ArrayList. If the element is not found, it returns -1.

Example:

Output:

In the example above, we created an ArrayList named arrayList and added three elements to it: an integer, a string, and a double.

ArrayList Class

The ArrayList class in C# is a part of the .NET Framework and is located in the System.Collections namespace. It is a dynamic data structure that represents a resizable array-like collection that can store elements of any data type. The ArrayList class is considered legacy, and in modern C# code, it is generally recommended to use the more type-safe and efficient List<T> class (generic list) instead.

Constructors

Constructors are special methods in a class that are called when an object of that class is created or instantiated. They are used to initialize the object and set its initial state. In C#, constructors have the same name as the class and do not have a return type (not even void). They can have parameters to accept values during object creation.

Constructors play a crucial role in the object-oriented programming paradigm, as they ensure that objects are properly initialized with the necessary data when they are created.

Properties

PropertyDescription
CountGets the number of elements stored in the ArrayList. Read-only property that accurately represents the element count.
CapacityGets or sets the total number of elements the ArrayList can hold before resizing. Read-write property for manual capacity adjustment.

Methods

Here are some of the common methods available in the ArrayList class.

MethodDefinition
AddAdds an element to the end of the ArrayList.
RemoveRemoves the first occurrence of a specific element from the ArrayList.
RemoveAtRemoves the element at the specified index in the ArrayList.
InsertInserts an element at the specified index in the ArrayList. Existing elements at or after the specified index are shifted to make room for the new element.
ContainsChecks if a specific element exists in the ArrayList.
IndexOfReturns the index of the first occurrence of a specific element in the ArrayList. Returns -1 if the element is not found.
ClearRemoves all elements from the ArrayList.
ToArrayCopies the elements of the ArrayList to a new array.

Example: Here' the C# code for above methods:

Output:

There are no items in the array because we have cleared the arrayList.

Conclusion

  • ArrayList is designed to be flexible in size, meaning you can add or remove elements without manually resizing the underlying array.
  • ArrayList can hold elements of different data types. This means we can add integers, strings, doubles, and other types of objects within the same ArrayList.
  • When we add value types (e.g., int, double) to an ArrayList, they are automatically converted into objects through a process called "boxing". Boxing involves wrapping the value type in an object so that it can be stored in the ArrayList.
  • Conversely, when we retrieve elements from an ArrayList, you need to "unbox" them back into their original value types. Unboxing involves extracting the value from the object and converting it back to the appropriate value type.
  • Internally, ArrayList uses an array of type object[] to store the elements. As a result, any element you add to the ArrayList is treated as an object, regardless of its original type.