Wednesday, July 18, 2012

Difference between Array and Arraylist in C#


System.Array
System.Collections.ArrayList
Arrays are strongly typed.

 That is all the elements have to be of the same type. For example an array of integers has to have all integers.  It cannot have a mix of integers and strings.
An arraylist is NOT strongly typed.

You can have a  combination of built in types  (int,string etc) in your arraylist.
Cannot be dynamically resized.

Note : Array.Resize() doesnot actually resize the existing array. It infact creates a new array with the required length and copies values from the old array to new array. Using the Resize is more memory intensive than AddRange() in arraylist
Can be dynamically resized
using the method Arraylist.AddRange()
Eg
int[] myIntArray = new int[3];
myIntArray[0]=10;
myIntArray[1]=20;
myIntArray[2] = "Thirty";//Compilation ERROR
Eg
ArrayList arraylist = new ArrayList();

 arraylist.Add("MyName");
 arraylist.Add(9);

No comments:

Post a Comment