What is the difference between array and arraylist in C#?
C# has two types of arrays. The first is an Array type, while the second is the ArrayList type. Although both types declare an array, there are some critical differences in the declared arrays.
Syntax
An array of type Array can be declared using the following syntax:
<datatype>[] <name> = {<data>};
<datatype>can be any user-defined or built-in data type.<name>is the defined array name.<data>is the elements stored in the array.
An array of type ArrayList can be declared using the following syntax:
ArrayList <name> = new ArrayList();
ArrayListis a built-in data type in C#.<name>is the defined array name.
Example
The following code snippets are examples of the two array types:
Array
class HelloWorld{static void Main(){char[] outputmessage = {'H','e','l','l','o',' ','W','o','r','l','d','!'};System.Console.WriteLine(outputmessage);}}
The outputmessage array with the Array type strictly stores one datatype only. If we try to add different data types, it will throw an error of conversion type:
class HelloWorld{static void Main(){char[] outputmessage = {'H',"ello ",'W',"orld!", 23, 5.6};System.Console.WriteLine(output);}}
To cater to multiple data types in a single array we use the ArrayList type.
ArrayList
//required namespace for ArrayListusing System.Collections;class HelloWorld{static void Main(){ArrayList outputmessage = new ArrayList();outputmessage.Add('H');outputmessage.Add("ello ");outputmessage.Add('W');outputmessage.Add("orld!");outputmessage.Add(2);outputmessage.Add(6.6);for(int i = 0;i< 6;i++){System.Console.Write(outputmessage[i]);}}}
Explanation
As seen from the above code snippets, there is a significant difference between the two types of arrays. The outputmessage array with the ArrayList type can have data of different types at each index. For example, the first index has 'H', a character type, while the second has "ello", a string type.
Differences
Below is a table that shows the most important differences between the two array types:
Array | ArrayList |
It is strictly typed (stores only one data type). | It can store multiple data types. |
It is faster. | It is comparatively slow. |
It requires the static helper class array to perform different operations on an array. | It has various utility methods to apply different operations to an array. |
It has a fixed size. | It grows dynamically. |
It does not need casting for retrieval. | It needs casting for retrieval. |
Free Resources