18 September 2013

Difference between Array and Arraylist in C# with Example



Arrays

Arrays are strongly typed collection of same datatype and these arrays are fixed length that cannot be changed during runtime. Generally in arrays we will store values with index basis that will start with zero. If we want to access values from arrays we need to pass index values.

Declaration of Arrays

Generally we will declare arrays with fixed length and store values like as shown below

string[] arr=new string[3];
arr[0] = "adi";
arr[1] = "dotnet";
arr[3] = "total";


In above code I declared array size 3 that means we can store only 3 string values in array.

Arraylists



Array lists are not strongly type collection. It will store values of different datatypes or same datatype. Array list size will increase or decrease dynamically it can take any size of values from any data type. These Array lists will be accessible with “System.Collections” namespace

Declaration of Arraylist

To know how to declare and store values in array lists check below code

ArrayList strarr = new ArrayList();
strarr.Add("welcome "); // Add string values
strarr.Add(20);   // Add integer values
strarr.Add(20.05); // Add float values

If you observe above code I haven’t mentioned any size in array list we can add all the required data there is no size limit and we will use add method to bind values to array list

Difference between Array and ArrayList


Arrays
ArrayLists
These are strong type collection and allow to store fixed length
Array Lists are not strong type collection and size will increase or decrease dynamically
In arrays we can store only one datatype either int, string, char etc…
In arraylist we can store all the datatype values
Arrays belong to System.Array namespace
Arraylist belongs to System.Collection namespaces



No comments:

Post a Comment