Saturday, 16 March 2013

  Generic List and ArrayList difference in c#?


                1. By using both the ArrayList and Generic List we can store any type of objects.Consider that you are intended to store only the integer values.In this case when we use ArrayList , we can store any type of objects(i.e.,  Integer,String or some custom objects).

Example:
ArrayList objarList=new ArrayList();
objarList.add(123);
objarList.add("senthil");// will compile..but throw run time error.

 It won't throw any compile time error.It will throw only run time error when we iterate values in the  array list by using for each.

But when we use the Generic List ,we can restrict in the compile time itself.If you are intended to store only integer values, it will allow to store only integer values.If you try to store any other value other than integer, then it will throw compile time error.

List<int> objList=new List<int>();
objList.add(123);
objList.add("senthil") // Will result in compile time error.

2.Whenever you are adding the objects in the ArrayList  , at that time boxing will happen.Whenever you are accessing the objects from the ArrayList , at that time unboxing will happen.So it will hurt the performance. But incase of Generic List there will not be any Boxing or UnBoxing problem and also it will provide the better type safety.

No comments:

Post a Comment