Wednesday, December 20, 2006

System.Collections.Generic

Generic is a new feature introduced in C#. It is nothing but a type-safe collection. Generic collection can store only items that are compatible with argument type specified in declaration. Moreover generic collection works in similar way like non-generic collection, only the difference is to mixed types are not allowed. Non-generic collections are useful in case if you want to mix-up unrelated data types. List, Dictionary are example of C# generics.

Example:

using System;
using System.Collections.Generic;

class GenericDemo
{
public static void Main()
{
List lstInteger =new List();

//Add elements to generic integer list
//Correct entry as per generic
lstInteger.Add(1);
lstInteger.Add(2);
lstInteger.Add(3);
lstInteger.Add(4);
lstInteger.Add(5);


//Code exception due to following wrong entry
lstInteger.Add(‘Kuldeep’);
}
}


Because of type-safety principle, in above example it will throw error at last lstInteger.Add(‘Kuldeep’) statement. Current declaration for generic is an integer and at last statement you'r trying to insert is a string type. So it will raise exception.

No comments:

Visitor Count: