ArrayList VS Generic List in C#



In this article I will explain the difference between C# ArrayList and Generic List<>. 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. So, there are following differences between arraylist and list:-

 difference between arraylist and List<>, ArrayList vs List<object>, create a List,ArrayList,List, ArrayList or Generic.List, Net framework, arraylist and List<> in c#,
C# ArrayList
  • 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();
            arrList.Add(02136);
            arrList.Add("Ravi Kumar");
            arrList.Add(DateTime.Now);

  • 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[0]);
            string name = arrList[1].ToString();
            DateTime dt = Convert.ToDateTime(arrList[2]);
  • 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>();
            lstString.Add("Ravi Kumar");
            lstString.Add("Kunal Singh");
            lstString.Add("Sachin Singh")
  • 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[0];
  •  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)
            {
            }

NoteI would recommend use Generic List in your projects if available.
Please leave your comments, suggestions and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading! :)

Post a Comment

 
Top