In this article· 30 sectionsJump to any section of the article
- 1Brief Introduction to ArrayList
- 2Comparison between ArrayList and Other Collections
- 3Working with Dimensions in ArrayList
- 4The Role of Arrays in Unity
- 5Introduction to Array Class in C#
- 6Understanding ArrayList Methods
- 7Intermediate Operations on ArrayList
- 8Dealing with Composite Collections
- 9Detailed Look at ArrayList of Objects in C#
- 10Wrapping up with ArrayLists
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 ArrayListArrayList myArrayList = new ArrayList();// Adding items to ArrayListmyArrayList.Add("One");myArrayList.Add(2);myArrayList.Add(3.14);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 ArrayListmyArrayList.Remove("One");// Check ArrayList sizeint count = myArrayList.Count; // Outputs 2Removing 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(); myArrayList.Add(1); myArrayList.Add("Two");// List requires type specificationList<int> myList = new List<int>();myList.Add(1);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 sizestring[] strArray = new string[3];strArray[0] = "One";strArray[1] = "Two";// ArrayList doesn't need a predefined sizeArrayList myArrayList = new ArrayList();myArrayList.Add("One");myArrayList.Add("Two");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# arrayint[] numArray = { 1, 2, 3, 4, 5 };// Convert array to ArrayListArrayList 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!
// ArrayListArrayList myArrayList = new ArrayList();myArrayList.Add(1);myArrayList.Add(2);myArrayList.Add(3);// Convert ArrayList to ListList<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 ArrayListArrayList arrList = new ArrayList();ArrayList innerList;innerList = new ArrayList();innerList.Add(1);innerList.Add(2);arrList.Add(innerList);innerList = new ArrayList();innerList.Add(3);innerList.Add(4);arrList.Add(innerList);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 ArrayListArrayList 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 examplepublic 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 ClassArray 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 sizeArrayList myArrayList = new ArrayList();myArrayList.Add(1);myArrayList.Add(2);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 ArrayListArrayList myArrayList = new ArrayList() { 1, 2, 3 };foreach (var item in myArrayList){ Console.WriteLine(item);}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 elementmyArrayList.Add(4);// Insert an elementmyArrayList.Insert(0, 0);// Remove an elementmyArrayList.Remove(2);// sort the ArrayListmyArrayList.Sort();// Iterating over an ArrayListforeach (var item in myArrayList){ Console.WriteLine(item);}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 ArrayListArrayList myArrayList = new ArrayList() { 1, 2, 3 };myArrayList.Remove(2);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 ArrayListArrayList myArrayList = new ArrayList();myArrayList.Add(1);myArrayList.Add(2);// 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 ArrayListArrayList myArrayList = new ArrayList() { 3, 1, 2 };myArrayList.Sort();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 arraysList<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 ListsList<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 ObjectsArrayList listOfObjects = new ArrayList();listOfObjects.Add(1);listOfObjects.Add("Two");listOfObjects.Add(3.14);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!



