Learning Of C# Arraylist for Beginners

Array list is the collection of different data types or objects. Array List is different from simple Array in a way that Arrays are used to insert the elements of same data type. In Array list we can store different data types and objects of different classes. Another difference is in the size. Size of Array List is not static i.e. it can vary according to our needs during run time.

In C# using of  array list is quite simple. The namespace using System.Collections.Generic must be used in order to use Array List and its functionality.

Initializing Array List:

ArrayList newlist = new ArrayList(); 

In this line we have initialized the object of Array List with the name newlist.

Adding Elements in the Array List:

int a=5;
//this line we have added object of DateTime class

Now we have added three elements of different data type and one object of DateTime class. Add() function from the Array List adds new item to the Array List.

Getting Size of the Array List:

int size=newlist.Count;

By using the property Count of Array List object we can get the size of Array List. As we have added three items because size of the Array List is 3. The size will be stored in a variable named size.

Accessing Items from the Array List:

The main task is to access the items back from Array List. One thing must be kept in mind while accessing the item that we have to cast each item into its proper data type or object.
As we have inserted integer first so we can access it from Array List as follows:

//0 based indexing
int b = (int)newlist[0];
string t=newlist[1] as string;
DateTime dt=(DateTime)newlist[2];


Clearing Array List:

We can clear and delete the all elements of list as follows.