다음을 통해 공유


C#: Difference between Array and Array List

The basic difference between an Array and ArrayList are:

  • Arrays are of fixed size, whereas ArrayList can grow dynamically in size.
  • Array occupies memory in Stack whereas ArrayList occupies Heap.
  • ArrayList are not type-safe, single ArrayList can contain different data types.

Let us go by a sample:

Step 1: Create a console application.

Step 2: Create an ArrList class as shown below.

public class  ArrList
 
   {
 
   public string  msg = "String of ArrList Class";
 
   string[] sl = new  string[3];  // Array is of fixed size, Type Safe
 
   ArrayList al = new  ArrayList();  // Array List size is dynamic , Not Type Safe
 
   public void  AddItem()
 
   {
 
   //Permissible members are string only
 
   sl[0] = "Hi";
 
   sl[1] = "Hello";
 
   sl[2] = "Welcome";
 
   //Permissible members are of any data type
 
   al.Add("String Msg");  //Adding String
 
   al.Add(1);  //Adding Integer
 
   al.Add('c');  //Adding Char
 
   ArrList ob = new  ArrList();
 
   al.Add(ob);  //Adding userdefined class instance
 
   }
 
   public void  ReadItem()
 
   {
 
   int i;
 
   Console.WriteLine("Printing Array");
 
   for (i = 0; i < 3; i++)
 
   {
 
   Console.Write(sl[i]+"//");
 
   }
 
   i = 0;
 
   Console.WriteLine("\n"+"Printing ArrayList");
 
   foreach (var itm in al)
 
   {
 
   Console.Write(itm + "//");
 
   }
 
   }
 
   }

Step 3: In the Main method, use the below code:

Console.WriteLine("//**********Array and ArrayList******************");
 
   ArrList myAr = new  ArrList();
 
   myAr.AddItem();
 
   myAr.ReadItem();