Translate

Saturday 28 June 2014

What is the difference between ArrayList and Generic List in C#?

Arraylist:
  1. It is like Array of objects.
  2. "System.Collections" is the Namespace for Arraylist. It automatically added to namespace section in aspx.cs page.
  3. We need not to specify object type arraylist going to contain.
  4. In arraylist each item is stored as object. And return value as object.
  5. It needs to box and unbox the elements.
  6. No type safety (Compile time)
List<T>:



  1. "System.Collections.Generic" is the Namespace for List. We need to add this.
  2. We need to specify object type which type of elements it contain. 
  3. Ex: List<string> StrObj=new List<string>();
  4. From the above example StrObj will only store string objects.
  5. It doesn't need.
  6. Type safety (compile time)
Example: 

namespace Example
{
   class Program

    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add("hello");
            list.Add(new Program()); // Oops! That's not meant to be there...
            list.Add(4);
            foreach (object o in list)
            {
                Console.WriteLine(o.ToString());
            }
            List<string > lstString = new List<string>();
            lstString.Add("ABCD");
            lstString.Add(new Program());   //Compiler error
            lstString.Add(4);   // Compiler Error
            foreach (object o in lstString)
            {
                Console.WriteLine(o.ToString());
            }  }

}


No comments:

Post a Comment