Difference Between Array And ArrayList In C#

In this article, we will learn Difference Between Array And ArrayList.

Array :

Arrays are strongly-typed collections of the same data type and have a fixed length that cannot be changed during runtime. We can access the Array elements by numeric index. The array indexes start at zero. The default value of numeric array elements is set to zero, and the reference elements are set to null.

Example of Array :

// creating array 
int[] arr = new int[4]; 
  
// initializing array 
arr[0] = 47; 
arr[1] = 77; 
arr[2] = 87; 
arr[3] = 97; 

// traversing array 
for (int i = 0; i < arr.Length; i++) 
{ 
   Console.WriteLine(arr[i]);
}

ArrayList :

Array list is not a strongly-typed collection. It can store the values of different data types or same datatype. The size of an array list increases or decreases dynamically so it can take any size of values from any data type. ArrayList is one of the most flexible data structures from C# Collections. ArrayList contains a simple list of values. ArrayList implements the IList interface using an array and very easily we can add, insert, delete, view etc.

Example of ArrayList:

// Create a list of strings 
ArrayList al = new ArrayList(); 
al.Add("Dhruv"); 
al.Add("Pole"); 
al.Add(50); 
al.Add(10.68); 
  
// Iterate list element using foreach loop 
foreach(var names in al) 
{ 
    Console.WriteLine(names); 
}

Difference Between Array and ArrayList

Array ArrayList
1.Must include System namespace to use array. 1.Must include System.Collections namespace to use ArraList.
2.Array is strongly typed. This means that an array can store only specific type of items\elements. 2.ArrayList can store any type of items\elements.
3.Array cant accept null. 3.ArrayList collection accepts null.
4.Performs faster than ArrayList because it is strongly typed. 4.Performs slows because of boxing and unboxing.
5.Array stores fixed number of elements. Size of an Array must be specified at the time of initialization. 5.ArrayList grows automatically and you don’t need to specify size.
6.In arrays we can store only one datatype. It’s generic type of collection 6.In ArrayList we can store all the datatype values. It’s non-generic type of collection

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories