Home | Feedback | Login

Array vs ArrayList

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections; // add this in order to use ArrayList
namespace Collections
{
    class Program
    {
        // Array is fixed length
        // Array is bound to specific datatype
        // Array is strong type and it faster
       
        // Arraylist uses system.collections
        // Arryalist is not bound to a fix length
        // Arraylist is not bound to specific datatype
        // Arraylist is slower because of generic datatype, boxing unboxing
 
        static void Main(string[] args)
        {
            string[] str = new string[5];
            int[] myint = new int[5];
            for (int i = 0; i < str.Length; i++)
            {
                str[i] = "abc"; // only accept string
                //str[i] = 4; // int cannot be converted to string
                Console.WriteLine(str[i]);
                
            }
 
            ArrayList arrlist = new ArrayList();
            for(int i = 0; i < 5; i++)
            {
                if (i % 2 != 0)
                    arrlist.Add("xyz"); // accept any data type
                else
                    arrlist.Add(i); // accept any data type
                Console.WriteLine(arrlist[i]);
            }
 
            Console.ReadLine();
        }
    }
}