Ways to use C# ArrayList with 4 demos

In This Tutorial

What is the ArrayList?

The ArrayList is a class of System.Collection namespace in C# which is just like the arrays. However, unlike simple arrays, the ArrayList in C# is dynamic.

That means you can add or remove elements from the ArrayList by using the index number dynamically. While arrays are fixed in size.

The ArrayList dynamically resizes itself as items are added or removed. Also, the ArrayList can contain mixed items like numbers and strings etc. in a single ArrayList, unlike a simple array.

See an ArrayList example

The C# ArrayList has its methods and properties that can be used to perform desired tasks like count, Capacity, Add, Clear, sort etc. We will show you examples of using the ArrayList class with its methods and properties in this tutorial, let us look at its syntax first.

Syntax to initialize an ArrayList

Following is the general syntax to create/initialize a C# ArrayList object:

ArrayList ArrLst = new ArrayList();

Where

  • The ArrayList is followed by the name of the object, ArrLst in that case.
  • You have to use the new keyword which is followed by the ArrayList and parenthesis.

As we learned, what ArrayList is and its syntax, let us look at a few examples of creating and using properties and methods of the ArrayList of C#.

An ArrayList example with the Add method

In this example, we will create an ArrayList object and its items. After that, we will use Add method of the ArrayList class to create items. Also, we will use ArrayList Count property to get the total count of array list in the for loop.

In that example, we will just assign numeric values and then use for loop to display ArrayList items.

ArrayList with mixed items example

In this example, we will create a C# ArrayList with mixed items i.e. numbers and strings. After creating a list, we will display ArrayList items by using a for loop. See example by clicking the link below:

You can see, we used numbers and strings in a single ArrayList C#. This is unlike simple arrays and list in C#, that uses strict type.

ArrayList example with foreach

In above examples, we used for loop to iterate through ArrayList. In this example, we are using the foreach loop to iterate through ArrayList items. See example by clicking the link below:

To learn more about c# foreach loop go to its chapter.

C# ArrayList sort method example

Following is an example of using the ArrayList sort method. For that, we have created an array with the unordered list.

In the example, we will first display ArrayList items in the same order as we created and then we used the sort method and displayed the ArrayList again.

You can see, the sort method sorted the ArrayList from lower to higher numbers.

Further Reading: C# list | C# Array

Was this article helpful?

Related Articles

Leave A Comment?