✨ Shield now has support for Avalonia UI

Implementing ArrayList in C#: Guide with Examples

Dec 29, 2023 | C#

Do you ever get confused between arrays and ArrayLists and how they function in C#? Or are you among those who get stuck with syntax while working with multidimensional ArrayLists? Well, you’re at the right place! This walkthrough will be your guide when you venture into the world of ArrayLists in C#. Shall we begin?

Brief Introduction to ArrayList

You might be asking, “What on earth is an ArrayList?” or “Why should I bother learning about it?”. The answers are not far from our grasp.

What is ArrayList in C#?

ArrayList is a non-generic collection class that we can use in C# to store multiple data items of the same or different types in a single container. This, my friends, is where the marvel of ArrayList in C# lies! It is quite versatile.

// Constructing an empty ArrayList
ArrayList myArrayList = new ArrayList();

// Adding items to ArrayList

This snippet gives you a taste of how to create an ArrayList and populate it. You can see it holds various data types in one place, from integers to strings. Pretty neat, right?

How to use ArrayList in C#?

The flexibility of ArrayList also shines through in its manipulation. Operating an ArrayList is as easy as pie, combining the ease of arrays and the convenience of lists.

// Remove an item from ArrayList

// Check ArrayList size
int count = myArrayList.Count;  // Outputs 2

Removing items and finding the size of the ArrayList, and many other operations, all at your fingertips! Moving on, let’s see how ArrayList compares with other collections.

Comparison between ArrayList and Other Collections

One may wonder, “Why choose ArrayList over traditional arrays or generic lists?” The trick is understanding the difference and then picking the most suitable tool for the job.

ArrayList vs List in C#

When it comes to ArrayList and List, the primary distinction lies within their nature. While ArrayList is non-generic, List in C# is a generic collection class. That means while ArrayList can store any object type, List requires a specific data type upon initialization.

// ArrayList stores any object type 
ArrayList myArrayList = new ArrayList();  

// List requires type specification
List<int> myList = new List<int>();

You might wonder why would you use List then? Well, List provides type safety, meaning you won’t accidentally add a string to a List of integers. Each has its pros and cons, choose wisely!

Difference between Array and ArrayList in C# with Example

The most notable difference here lies in their nature. Arrays in C# are statically-typed while ArrayLists are dynamically-sized. Sounds confusing? Let’s clear it up with some good ol’ code examples.

// Array must have a predefined size
string[] strArray = new string[3];
strArray[0] = "One";
strArray[1] = "Two";

// ArrayList doesn't need a predefined size
ArrayList myArrayList = new ArrayList();

While arrays require you to define its size beforehand, ArrayLists free you from this constraint. Fair trade-off for array’s type safety, isn’t it?

Array to ArrayList Conversion in C#

“I have an array but would like the dynamic benefits of an ArrayList. Any solutions?” Of course! You can easily convert your array to an ArrayList.

// C# array
int[] numArray = { 1, 2, 3, 4, 5 };

// Convert array to ArrayList
ArrayList numArrayList = new ArrayList(numArray);

Simple enough? Next, let’s see what happens when you decide to convert back.

Converting ArrayList to List

“What if I want to ensure type safety and decide to convert my ArrayList to a List?” you might wonder. Fear not, C# has you covered!

// ArrayList
ArrayList myArrayList = new ArrayList();

// Convert ArrayList to List
List<int> myList = myArrayList.Cast<int>().ToList();

With just a line of code, you can ensure type safety for your ArrayList. Pretty handy, right?

Working with Dimensions in ArrayList

Ever thought of building a multi-dimensional data structure using ArrayList? Well, you’ve hit the jackpot here!

Understanding 2 Dimensional ArrayList in C#

2D ArrayList in C# allows you to store data in rows and columns. Imagine your ArrayList as a matrix, filled with data!

// Creating a 2D ArrayList
ArrayList arrList = new ArrayList();
ArrayList innerList;

innerList = new ArrayList();

innerList = new ArrayList();

In the given example, we have an ArrayList ‘arrList’ with two elements. Each element is another ArrayList, thus implementing a 2D ArrayList. Mind-blowing, right?

Implementing 2D ArrayList in C#

With implementation, the game gets a tad bit complex but a thousand times more exciting!

// Accessing elements in 2D ArrayList
ArrayList arrList = new ArrayList();
int firstElement = ((ArrayList)arrList[0])[0];

Remember, a 2D ArrayList stores ArrayLists as elements, so you need to downcast the first ArrayList before accessing the elements.

The Role of Arrays in Unity

Countless gaming experiences would fall flat if it wasn’t for Unity’s ability to handle arrays. How? Let’s find out!

Understanding Array in C# Unity

In Unity, arrays are used to handle multiple data of the same type. A game with hundreds of characters? An array can handle that!

// Unity array example
public int[] scoreArray = new int[5];

In a typical Unity setup, this line of code declares an array of ‘scoreArray’ with a length of 5 to keep track of scores.

Introduction to Array Class in C#

Now, let’s dive into the beauty of the Array Class in C#. What’s that? Let’s find out!

Exploring Array Class in C#

An Array Class can be your secret weapon when you’re mulling over multidimensional or dynamic arrays! You might wonder, “Arrays within arrays? How cool is that!”, and you would be totally right!

// Multidimensional dynamic array with Array Class
Array myArray = Array.CreateInstance(typeof(String), 2, 2);
myArray.SetValue("First", 0, 0);
myArray.SetValue("Second", 0, 1);

This example demonstrates an Array, appropriately named ‘myArray’, created as a 2×2 dynamic array. You’re exploring new frontiers, aren’t you?

Understanding ArrayList Methods

Hold on to your hats, folks! We’re delving into a few amazing built-in methods that can help manage your ArrayLists.

Getting the Count of Elements in ArrayList

Before diving into bigger operations, it’s often critical to know the size of your ArrayList.

// Checking ArrayList size
ArrayList myArrayList = new ArrayList();
int count = myArrayList.Count;

In the snippet above, the ‘Count’ property of ArrayList ‘myArrayList’ returns the number of items stored in it. Isn’t it amazing how such minute details can shape our code?

Iterating through ArrayList with ForEach in C#

Enumeration is an essential aspect when working with ArrayLists. Thankfully, C# provides a very convenient ‘ForEach’ loop for such tasks.

// Iterating over an ArrayList
ArrayList myArrayList = new ArrayList() { 1, 2, 3 };
foreach (var item in myArrayList)

With the use of ‘ForEach’, we’re effortlessly cycling through each element in ‘myArrayList’. Ready yet to immerse deeper?

Overview of ArrayList Methods in C#

While ‘Count’ and ‘ForEach’ are just the surface, there’s a whole world to discover with ArrayList methods! Here’s a sneak peek:

  • Add: Add an element at the end of an ArrayList
  • Insert: Insert an element at a specific index in an ArrayList
  • Remove: Remove the first occurrence of a specific element
  • Sort: Sorts the elements in the entire ArrayList
  • Reverse: Reverses the order of elements in the entire ArrayList
ArrayList myArrayList = new ArrayList() { 1, 2, 3 };
// Add an element
// Insert an element
myArrayList.Insert(0, 0);
// Remove an element
// sort the ArrayList
// Iterating over an ArrayList
foreach (var item in myArrayList)

Each method contributes uniquely to ease, maintainability, and readability of your code. It’s as though they have a life of their own!

Intermediate Operations on ArrayList

There’s more to ArrayList than just adding and enumerating elements. As we dive deeper, we’ll explore some more handy operations.

How to Remove Elements from an ArrayList in C#

Removing elements from an ArrayList is as important as adding them. The ‘Remove’ method is at your rescue!

// Removing an item from an ArrayList
ArrayList myArrayList = new ArrayList() { 1, 2, 3 };

This example shows how simply you can remove an element — just call ‘Remove’ and pass the value. Smooth as silk!

Working with ArrayList Size in C#

After operations like ‘Add’ and ‘Remove’, you might need to review the size of your ArrayList. That’s where ArrayList properties like ‘Count’ and ‘Capacity’ come to play.

// Checking size of an ArrayList
ArrayList myArrayList = new ArrayList();
// Get the number of elements in the ArrayList (Count)
int count = myArrayList.Count;
// Get the total number of elements the internal data structure can hold without resizing (Capacity)
int capacity = myArrayList.Capacity;

While ‘Count’ gives you the total elements present in the ArrayList, ‘Capacity’ tells the maximum size it can reach before needing resizing. Sounds like secret superpowers, doesn’t it?

Sorting Elements within an ArrayList

An organized ArrayList is much easier to manage, and sorting takes care of that.

// Sorting an ArrayList
ArrayList myArrayList = new ArrayList() { 3, 1, 2 };

With ‘Sort’, your ArrayList elements will self-arrange in ascending order. It’s like magic!

Dealing with Composite Collections

Arrays or Lists as elements of another collection? Why not!

Working with List of Arrays in C#

A List of Arrays in C# takes you a step forward from a simple ArrayList or List.

// Creating a List of arrays
List<int[]> listOfArrays = new List<int[]>();

With this format, each item of the list is an array. It’s basically arrays within a list. Cool, isn’t it?

Understanding Array of Lists in C#

Let’s flip the narrative now — what about an array where each element is a List?

// Creating an array of Lists
List<int>[] arrayOfLists = new List<int>[3];

What we just saw is an array ‘arrayOfLists’ where each of its elements can potentially be a list. Arrays of lists, Lists of arrays — the amalgamation possibilities are endless!

Detailed Look at ArrayList of Objects in C#

An ArrayList of Objects takes things up a notch. An Object to hold different types? You got it!

// Creating an ArrayList of Objects
ArrayList listOfObjects = new ArrayList();

You can see the ArrayList accommodating all sorts of data. Such a classy case for polymorphism!

Wrapping up with ArrayLists

With lots of information on ArrayLists, let’s conclude with a quick recap and some best practices.

What is the Difference Between Array and ArrayList in C#?

We’ve seen earlier that an Array’s size needs to be specified during initialization and it is type-specific, while an ArrayList’s size can change dynamically and holds different data types. Pretty close to decision factors, aren’t they?

Best Practices when Using ArrayLists in C#

Finally, remember to:

  • Use ArrayList instead of Array when you need a dynamically-sized collection.
  • Use List or other generic collections when type-safety is important.
  • Make proper use of ArrayList methods and properties to write cleaner and efficient code.
  • Consider using more advanced data structures like HashSet, Stack, Queue, or Dictionary if they fit your use-case better.

There you have it, folks — a complete guide to ArrayList in C#. With each line of code written, each snippet run, you’ve built up a robust building block for your programming journey. Now, get out there and show your ArrayList prowess!

You May Also Like