Tuesday, August 26, 2008

Sample for Generic Collections

Suppose if we want to store collection of integer, then we could write code something like,
ArrayList MyList = new ArrayList();
MyList.Add(1);
MyList.Add(2);

It will work good. Suppose if we add like,
MyList.Add("3");
It will compile without error. If we loop through each item and converting it to integer we will got exception thrown.

To avoid this we will go for Generic Type
ArrayList Equivalent Generic Type is List

List MyList = new List();
MyList.Add(1);
MyList.Add(2);
MyList.Add("3"); ---> this will give you complier Error

No comments: