In C#, an Array
is a collection of items that are stored in a contiguous block of memory. It is a fixed size, meaning that you must specify the size of the array when you create it, and you cannot change the size of the array later. Arrays are also index-based, meaning that you access items in the array using an integer index. Example:
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
int x = numbers[0]; // x is now 1
int y = numbers[1]; // y is now 2
On the other hand, an ArrayList
is a type of collection that is similar to an array, but it is dynamically sized, meaning that you can add or remove items from the list and the size of the list will automatically adjust. Like an array, an ArrayList
is index-based, so you can access items in the list using an integer index. However, an ArrayList
can store items of any type, whereas an array can only store items of a single, specified type. Here is an example of how to create and use an ArrayList
in C#:
ArrayList list = new ArrayList();
list.Add(1);
list.Add("Hello");
list.Add(true);
int x = (int)list[0]; // x is now 1
string y = (string)list[1]; // y is now "Hello"
bool z = (bool)list[2]; // z is now true
In summary, the main differences between Array
and ArrayList
in C# are:
Array
is fixed size, whereasArrayList
is dynamically sized.Array
can only store items of a single, specified type, whereasArrayList
can store items of any type.