ArrayList vs List in C#

  1. ArrayLists in C
  2. Lists in C
  3. ArrayLists vs Lists in C

This tutorial will discuss the differences and similarities between ArrayLists and Lists in C#.

ArrayLists in C

The ArrayList class is used to declare an ArrayList in C#. An ArrayList stores object references in it. This means that an ArrayList can store data of multiple data types like integer, string, float, etc., in it. The following code example shows us how we can initialize an ArrayList in C#.

ArrayList array1 = new ArrayList();
array1.Add(1);
array1.Add("Pony");
foreach (var x in array1)
{
    Console.WriteLine(x);
}

Output:

1
Pony

In the above code, we created the instance of ArrayList class array1 and stored different values of different data types in it.

Lists in C

The generic lists are used to hold data for one specific data type in C#. The List class is used to declare a list of a specific data type in C#. We need to specify the data type of our list during declaration. The following code example shows us how we can initialize a List in C#.

List<int> list1 = new List<int>();
list1.Add(1);
list1.Add(2);
foreach (var x in list1 )
{
    Console.WriteLine(x);
}

Output:

1
2

In the above code, we created the instance of List class list1 that holds integer data type and stored integer values.

ArrayLists vs Lists in C

The List class must always be preferred over the ArrayList class because of the casting overhead in the ArrayList class. The List class can save us from run-time errors faced due to the different data types of the ArrayList class elements. The lists are also very easy-to-use with Linq. The problem with array lists is shown in the following coding example.

ArrayList arrayExample = new ArrayList();
arrayExample.Add(2);
arrayExample.Add("DelftStack");
int total = 0;
foreach (int num in arrayExample)
{
    total += num;
}

The above code will give no error during compiling when we add the value DelftStack in our array list. But we will face a runtime error because we want to cast the DelftStack to the integer variable num. The problem can be avoided with the simple use of a list instead of an array list.

List<int> listExample = new List<int>();
listExample.Add(1);
listExample.Add(2);
int total = 0;
foreach (int num in listExample )
{
    total += num;
}

The above code will run perfectly without any errors. A list would give us a compile-time error whenever we try to add DelftStack to our list that only holds values of the integer data type.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp List

  • Compare Two Lists in C#