Generic Collection

Rajni.Shekhar
Posted by Rajni.Shekhar under C# category on | Points: 40 | Views : 1913
Generic Collection: If you want to retrieve a specific type of object, you need to cast that object into its real type. So generic collection solves this problem, by using generic collection, you no need to cast to its real type. generics are type safty.

for example, there is a ArrayList collection to store items of any type in the form of object. (As in .net everything can be represent as object)
But if you want to store a collection of integer, then without using generic you could do this job like:

ArrayLisy arrInt=new ArrayList();
arrInt.Add(1);
arrInt.Add(2);
arrInt.Add(3);

foreach(Object obj in arrInt)
{
int number=(int)obj; //need to type casting.
}

to avoid this type casting use generic collection:

public class MyList<T> : ICollection, IEnumerable
{
private ArrayList _innerList = new ArrayList();
public void Add(T val)
{
_innerList.Add(val);
}
public T this[int index]
{
get
{
return (T)_innerList[index];
}
}

MyList<int> myIntList = new MyList<int>();
myIntList.Add(1); //you can add only integers in myIntList

If you want to add string here, will get compiler error

MyList<String> myStringList = new MyList<String>();
myStringList.Add("1");

If you want to add int here, will get compiler error

Comments or Responses

Login to post response