Collection Types - C# Generic List and ArrayList
A System.Collections.ArrayList or System.Collections.Generic.List<T> object is a sophisticated version of an array. The ArrayList class and the List<T> generic class provide some features that are offered in most System.Collections classes but that are not in the Array class.
Difference Between ArrayList and List
In this article I will share the difference between C# Generic List and ArrayList with example and how to decide which one to use?
- To use ArrayList you need to import the namespace using System.Collections;
- It is not Type Safe i.e. you can store anything in ArrayList like int, string and datetime etc. In fact it can store multiple types of objects. For example:
ArrayList arrList = new ArrayList();
- ArrayList stores all data as object thus to get it back you must remember what you stored where and correspondingly Type Cast it as per its original Type when stored. For example:
int number = Convert.ToInt32(arrList);
string name = arrList.ToString();
DateTime dt = Convert.ToDateTime(arrList);
- While running a Loop on ArrayList you need to use Object data type. Thus this is another disadvantage as you again do not know what type of data particular item contains. For example:
foreach (object o in arrList)
C# Generic List (List<T>)
- To use generic list you need to import namespace using System.Collections.Generic
- In Generic List (List<T>), T means data type like int, string and datetime etc. It is Type Safe thus it will store only specific types of objects based on what data type has been specified while declarations. For example if we create a generic list of string data type there we can store string values only otherwise it will give compilation error. For example:
List<string> lstString = new List<string>();
- Generic List stores all data of the data type it is declared thus to getting the data back is hassle free and no type conversions required. For example:
string name = lstString;
- While running a Loop on Generic List again it is problem free as we exactly know what the List contains. For example:
foreach (string name in lstString)
Note: I would recommend use Generic List in your projects if available.
Conclusion: It was fun in learning and writing an article on Collection Types - C# Generic List and ArrayList. I hope this article will be helpful for enthusiastic peoples who are eager to learn and implement some interesting stuffs in new technology.
Please feel free to comment your opinion about this article or whatever you feel like telling me. Also if you like this article, don't forget to share this article with your friends. Thanks!
Collection Types - C# Generic List and ArrayList Reviewed by Ravi Kumar on 3:53:00 PM Rating: