.NET Technical bits: Difference between ArrayList and Generic List

Tuesday, November 30, 2010

Difference between ArrayList and Generic List

Here we will see some important differences for the collections ArrayList() and Generic List

ArrayList:

  • The namespace for ArrayList is System.Collections

  • How to create ArrayList?


    ArrayList stringArrayList = new ArrayList();

    Here we dont need to specify object type arraylist going to contain,store different type of objects or items



  • In ArrayList each item is stored as an Object so while reteriving we can get object only.

  • It is like Array of Objects.


Generic List:

  • The namespace for Generic List is System.Collections.Generic

  • How to create a List?


    List stringList = new List();

    i.e.


    List<type> nameOfList = new List<type>();


    type means object type which List<T> going to hold.



  • In List<T> , it can hold or contain only type of object which is mentioned while initialising the List<T>
    Just like in above example stringList will only contain object of type string, the type supplied as generic parameter.


  • It is newly added in .Net 2.0 and onwards, processing will be fast and no need of explicit casting.



Let us see one example.

string first = “First String”;

string second = “Second String”;

int firstInt = 1;

int secondInt = 2;

ArrayList stringArrayList = new ArrayList(); // No need to specify the object type,can store anything.

stringArrayList.Add(first); // string type

stringArrayList.Add(second); // string type

stringArrayList.Add(firstInt); // Can contain any type so no problem in storing int


List stringList = new List(); // Need to specify the object type, will contain only string types.

stringList.Add(first);

stringList.Add(second);


See this sample

stringList.Add(firstInt); // adding int in string type List.


we will get the exceptions below as List need to contain only string types. others are not allowed.


1) ‘The best overloaded method match for ‘System.Collections.Generic.List.Add(string)’ has some invalid arguments’

2) ‘Argument ’1′: cannot convert from ‘int’ to ‘string’


See another Sample


string abcd = stringArrayList[1];


Suppose if we try to get an ArrayList item without using the casting then we can get following exception, as arraylist contain Objects only we need to cast as pre our requirments.

We will get Exception –


‘Cannot implicitly convert type ‘object’ to ‘string’. An explicit conversion exists (are you missing a cast?)’


We can avoid it as


string abcd = stringArrayList[1].ToString(); // Needs casting ,memory overhead.


No comments:

Post a Comment