ArrayList
in c# is. Infact, some of us don't even know that ArrayList
exists.
Here in this post, I'm going to tell you guys the difference between ArrayList and Arrays in C#. You can directly jump over to differences section if you know what an Array and ArrayList is.
Array
Basically, an Array is a datatype, which used to store similar kind type of data and there are many types of arrays.
For example:
//single-dimension arrayint[]singleDimension=newint[5];// Declare a two dimensional arrayint[,]multiDimensionalArray=newint[2,3];// Declare a jagged arrayint[][]jaggedArray=newint[3][];
ArrayList
ArrayList is a class which implements an IList interface. So this can be called as datatype collection. Basically, ArrayList also makes use of the array under the hood to work. The speciality about ArrayList is that the size of the array list increases by one, each time an item is added to the list.
Example of ArrayList:
ArrayListarrayList=newArrayList();arrayList.Add("Hello World");
Differences between Array and ArrayList
Array | ArrayList |
---|---|
Defined in System namespace | Defined in System.Collections namespace |
Used to define similar type of data structures | Can handle multiple types in a single list |
Fixed length | length is incremented when an object is added to the list. |
Strongly typed | Not strongly typed |
Better when the size of the array is limited | Can be used when the size of the items is unknown. |
Arrays can be multidimensional | ArrayList is single dimensional |
No casting needs for retrieval or insertion of an item | Casting is required to retrieve the item from the list |
Performance Issues in Array List
ArrayList is introduced in .Net Framework 1.1. Although ArrayList gives a better way to handle the size of an array dynamically, it is barely used in daily programming because of performance.
The degraded performance is due to boxing and unboxing of items into/from ArrayList. When an item of type string is added to ArrayList, it is stored as an object in the list. So, to retrieve the value you need to unbox it with the given type. Let's consider the above piece of code, which adds "Hello World" to the arrayList.
To retrieve the value at 0th (zeroth) index
varhello=(string)arrayList[0];//castingisrequired
As ArrayList converts everything to object, it has to perform boxing during write and unboxing during read for whatever the type of the item be. This is a major performance drawback using the Array List in c#.
It is advisable to better go for List<T>
instead of using ArrayList. Since .NET 2.0 List
Conclusion
Though the ArrayList is not worth using, it is worth knowing the flaws of ArrayList.
Let me know your thoughts below.
Thanks