Thursday, 7 July 2011

List Vs Array list in C#

1)Array List

1)It always requires a conversion to object type. You can contain only object types in an array list. It is an overhead when dealing with large amount of datas.
2) It is a "Collection"
3) You can contain any type of data into an array list.


2)List
1)It does'nt requires an explicit conversion.
2) It is a type of "Generics"
3) You can save only one type of data in a List.

For eg::
ArrayList myArrayList = new ArrayList();
            //when we add a value(string type, integer type etc) to an array list, it is
            //first converted to type "object. Then saves it in the ArrayList

myArrayList.Add("it is a string");
            // this is a string type.So it is converted like this :-  ((object)"it is a string")
myArrayList.Add(1);
            // this is an integer type.So it is converted like this ((object) 1)
foreach (string str in myArrayList)
      Console.WriteLine(str);
//when we iterate through myArrayList each objects in this array list is casted to string type by unboxing.
foreach(string str  in myArrayList)
            Console.WriteLine(((string) str));
          
List<int> myList = new List<int>();
myList.Add(1);
myList.Add(2);
            //myList.Add("This is an error"); You cannot add string in an integer list
foreach (int _myList in myList)
     Console.WriteLine(_myList);
                        // This does'nt need unboxing. Because its data type is specified at the time of List                declaration.

So i would like to suggest List over ArrayList for performance optimization .

No comments:

Post a Comment