Major difference between ArrayList and List
ArrayList in C#
ArrayList -
1) Namespace System.Collections contain ArrayList ( This namespace is added by default when we creat any aspx page in C#)
2) Create ArrayList :
ArrayList stringArrayList = new ArrayList();
Here we don’t need to specify object type arraylist going to contain,store different type of objects/items/
3) ArrayList stores everything as an object, and when you retrieve the value you have to cast it back into the actual object type if you want to use any of the objects methods, etc.
4) It is like Array of Objects.
List<T> -
1) Namespace System.Collections.Generic List<T> (we need to add namespace if we want to use Generic Types)
2) Create List<T>:
List<string> stringList = new List<string>();
i.e.
List<type> nameOfList = new List<type>(); & type means object type which List<T> going to hold.
3) List<T> is a generic container type that you specify what type it can hold when you instantiate the List<T>. You don't have to cast the object back into the type.
4) It is newly added in .Net 2.0 & onwards, fast processing no need of casting explicitly.
ArrayList in C#
The Add method on ArrayList is used in almost every program. It appends a new element object to the very end of the ArrayList. You can keep adding elements to your collection until memory runs out. The objects are stored in the managed heap.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AbstractCLass
{
class Class_Main
{
static void Main(string[] args)
{
ArrayList objArrayList = new ArrayList();
objArrayList.Add("C#");
objArrayList.Add(".Net");
objArrayList.Add("By Sameer");
ExampleOfArrayList(objArrayList);
}
static void ExampleOfArrayList(ArrayList objArrayList)
{
foreach (string List in objArrayList)
{
int i = objArrayList.Count;
Console.WriteLine("Elements in Array List are"+List);
}
}
}
}
------------------------------------------------------------------------------------------------
List in C#
List in C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AbstractCLass
{
class Class_Main
{
static void Main(string[] args)
{
List<string> Employee = new List<string>();
Employee.Add("C#");
Employee.Add("By");
Employee.Add("SameeR");
ExampleOfArrayList(Employee);
Console.ReadLine();
}
static void ExampleOfArrayList(List<string> objList)
{
foreach (string List in objList)
{
int cnt = objList.Count;
Console.WriteLine("Elements in List are" + List);
}
}
}
}