TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

An Introduction To Generics In C#

Generics are type Safe,strongly typed Collections like normal arrays.Means it allows only one type of object to be stored in it and avoids the common type casting hassles of Arraylist.Also Generic collections improve the performance by overcoming the boxing/unboxing requirement.

 Arrays are general type of collection available in almost all programing languages.In C# from beginning there is a new set of collection called Arraylist,somewhat similar to conventional Array but offers some more enhanced features like growing the size of the array automatically.In Arraylist you can store any type of object.Till .NET 2.0 Arraylist is the extensively used collection in C# even though it is having some major performance drawbacks like the need of boxing and unboxing of each and every item stored in that collection.

With the release of C#  version 2.0,the concept of Generic Collection got introduced to overcome the drawbacks of Arraylist.

Generics are type Safe,strongly typed Collections like normal arrays with additional capability of dynamic size increase.Type safety is to prevent type erors.Means it allows only one type of object to be stored in it and avoids the common type casting hassles of Arraylist.Also Generic collections improve the performance by overcoming the boxing/unboxing requirement.

Very basic example of Generic collections available as inbuilt in .NET  is List.List can be used to store any one type of items, primitive types or reference type objects.

 

//Here intList is a collection which can only store int values
List<int> intList = new List<int>();


// Here stringList is a collection which can only store string values
List<string> stringList = new List<string>();


// employeeList is a collection which can only store Employee class objects
List<Employee> employeeList = new List<Employee>();


 Another commonly used inbuilt generic collection in .NET is Dictionary.Dictionary is a key-value pair collection where in key is unique.

// both key and value string
Dictionary<string,string> stringDictionary = new Dictionary<string,string>();   


 // Key as string and value int
Dictionary<string,int> intValueDictionary = new Dictionary<string,int>();         


 // Key as int and value as custom class object
Dictionary<int,Employee> customObjectDictionary = new Dictionary<int,Employee>();

 

Nullable Types

 

 

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading