Generics And Generic Collections In C#

Introduction

Generic collection is the most important concept in .NET, many of the programmers feel that Generic Collections are very complex, but after reading this article you will feel easy and comfortable to use these Generics and Generic collection.

In this article I have explained both Generic and Generic collection using simple samples, I hope this article will be useful in your daily life.

Problem with Array and ArrayList

Array

  • Arrays are strongly typed (meaning that you can only put one type of object into it).
  • Limited to size (Fixed length).

ArrayList

  • ArrayList are strongly typed.
  • Data can increase on need basis.
  • It will do the boxing and unboxing while processing (decrease the performance).

List (Generic Collection)

  • List are strongly typed.
  • Data can increase on need basis.
  • Don't incur overhead of being converted to and from type object.

Generic Collection

A generic collection is strongly typed (you can store one type of objects into it) so that we can eliminate runtime type mismatches, it improves the performance by avoiding boxing and unboxing.

Generic

Generic is the key concept to develop Generic collection.

In the following example we have created function Compare which will accept only integer values to compare, it won’t accept the other types like string, float, etc.

  1. NormalCheck obj = new NormalCheck();  
  2. int result = obj.Compare(2, 3);  
  3. class NormalCheck  
  4. {  
  5.     public bool Compare(int a, int b)  
  6.     {  
  7.         if (a == b)  
  8.         {  
  9.             return true;  
  10.         }  
  11.         else  
  12.         {  
  13.             return false;  
  14.         }  
  15.     }  
  16. }  
Generic Sample

Using Generic method we can define a function and it can accept all types of the object at runtime.

In the following example I am passing UnknowDataType to the class same passed in the Compare function to accept any datatype at runtime.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace Generics  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.             {  
  11.                 // Compare Integer  
  12.                 Check < int > obj1 = new Check < int > ();  
  13.                 bool intResult = obj1.Compare(2, 3);  
  14.                 // Compare String  
  15.                 Check < string > obj2 = new Check < string > ();  
  16.                 bool strResult = obj2.Compare("Ramakrishna""Ramakrishna");  
  17.                 Console.WriteLine("Integer Comparison: {0}\nString Comparison: {1}", intResult, strResult);  
  18.                 Console.Read();  
  19.             }  
  20.             // Generic class to accept all types of data types  
  21.         class Check < UnknowDataType >  
  22.         {  
  23.             // Gerefic function to compare all data types  
  24.             public bool Compare(UnknowDataType var1, UnknowDataType var2)  
  25.             {  
  26.                 if (var1.Equals(var2))  
  27.                 {  
  28.                     return true;  
  29.                 }  
  30.                 else  
  31.                 {  
  32.                     return false;  
  33.                 }  
  34.             }  
  35.         }  
  36.     }  
  37. }  
Output

run

Generic Collection

The following table is the generic collection for each .NET  Collection.

 

.Net Collection Generic Collection
Array list List (Generic)
Hash table Dictionary
Stack Stack Generics
Queue Queues Generics

Generic Collections Sample

The following example gives sample code for each Generic collection (How to declare and retrieve the data from that).

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace GenericCollectionSample  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             // index based generic collection (arraylist)  
  12.             List < int > listObj = new List < int > ();  
  13.             listObj.Add(123);  
  14.             listObj.Add(235);  
  15.             // Displaying list value using index  
  16.             Console.WriteLine("List Second Value: {0}", listObj[1]);  
  17.             // Key based generic Collection (Dictionary)  
  18.             Dictionary < intstring > objDic = new Dictionary < intstring > ();  
  19.             objDic.Add(123, "Ramakrishna");  
  20.             // Displaying Dictionary value using Key  
  21.             Console.WriteLine("Dictionary Value: {0}", objDic[123]);  
  22.             // Priority based Generic Collection (Stack)  
  23.             Stack < int > objStack = new Stack < int > ();  
  24.             objStack.Push(1);  
  25.             objStack.Push(2);  
  26.             objStack.Push(3);  
  27.             // Display first value from Stack  
  28.             Console.WriteLine("First Get Value from Stack: {0}", objStack.Pop());  
  29.             // Priority based Generic Collection (Queues)  
  30.             Queue < int > objQueue = new Queue < int > ();  
  31.             objQueue.Enqueue(1);  
  32.             objQueue.Enqueue(2);  
  33.             objQueue.Enqueue(3);  
  34.             // Display first value from Stack  
  35.             Console.WriteLine("First Get Value from Queue: {0}", objQueue.Dequeue());  
  36.             Console.WriteLine();  
  37.             // Creating Employee records  
  38.             Employee empObj1 = new Employee();  
  39.             empObj1.ID = 1001;  
  40.             empObj1.Name = "Ramakrishna";  
  41.             empObj1.Address = "Hyderabad";  
  42.             Employee empObj2 = new Employee();  
  43.             empObj2.ID = 1002;  
  44.             empObj2.Name = "Praveenkumar";  
  45.             empObj2.Address = "Hyderabad";  
  46.             // Creating generic List with Employee records  
  47.             List < Employee > empListObj = new List < Employee > ();  
  48.             empListObj.Add(empObj1);  
  49.             empListObj.Add(empObj2);  
  50.             // Displaying employee records from list collection  
  51.             foreach(Employee emp in empListObj)  
  52.             {  
  53.                 Console.WriteLine(emp.ID);  
  54.                 Console.WriteLine(emp.Name);  
  55.                 Console.WriteLine(emp.Address);  
  56.                 Console.WriteLine();  
  57.             }  
  58.             Console.Read();  
  59.         }  
  60.         public class Employee  
  61.         {  
  62.             public int ID;  
  63.             public string Name;  
  64.             public string Address;  
  65.         }  
  66.     }  
  67. }  
Output

Output