What are the advantages and disadvantages of using collection classes present in System.Collections namespace
We will understand the advantages and disadvantages of using collection classes present in System.Collections namespace, using ArrayList collection class. The same advantages and disadvantages apply to all other collection classes like Stack, Queue and Hashtable classes.
Advantages of using ArrayList:
1. ArrayList can grow in size dynamcally. In the example below, the Numbers ArrayList initial size is set 2. But we have added 3 elements. This proves that ArrayList, and the rest of the collection classes like Stack, Queue and Hashtable can grow in size dynamically. If Numbers, was an integer array, then we would have run into Index Out of Range compiler error.
2. ArrayList provide several convinient methods to add and remove elements to the collection. You can use the Add(), Remove() etc which are very handy to add and remove elements respectively. Similarly the Stack, Queue and Hashtable classes have thier respective methods, to add or remove the elements.
Disadvantages of using ArrayList:
ArrayList and all other collection classes like stack, queue and hashtable which are present in System.Collection namespace operate on object and hence are loosely typed. The loosely typed nature of these collections make them vulnerable to runtime errors. Click here for an example on how the loosely typed nature of an ArrayList can cause runtime erros.
Loosley typed collections can also cause performance overhead, because boxing and unboxing happens. In the example below, Numbers is an arraylist. We are stroing 10 and 20 which are integers and value types. Since, arraylist operate on object type, and object type is a
reference type, the value 10 is boxed and converted into a reference type. The same is the case with integer 20. If we store 100 integers in the arraylist. All the 100 intgers are boxed, meaning converted into reference types and then stored in the collection.
When we try to retrieve the elements out of the collection, we covert the object type back to integer type, unboxing happens. So this unnecessary boxing and unboxing happens behind the scenes everytime we add and remove value types to the collection classes present in System.Collections namespace. This can severly affect the performance, especially if your collections are large. To solve this problem, we have generics introduced in dotnet. Click here for the advantages and disadvantages of using generics.