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.

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.

NormalCheck obj = new NormalCheck();  
int result = obj.Compare(2, 3);  
class NormalCheck  
{  
    public bool Compare(int a, int b)  
    {  
        if (a == b)  
        {  
            return true;  
        }  
        else  
        {  
            return false;  
        }  
    }  
}

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.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
namespace Generics  
{  
    class Program  
    {  
        static void Main(string[] args)  
            {  
                // Compare Integer  
                Check < int > obj1 = new Check < int > ();  
                bool intResult = obj1.Compare(2, 3);  
                // Compare String  
                Check < string > obj2 = new Check < string > ();  
                bool strResult = obj2.Compare("Ramakrishna", "Ramakrishna");  
                Console.WriteLine("Integer Comparison: {0}\nString Comparison: {1}", intResult, strResult);  
                Console.Read();  
            }  
            // Generic class to accept all types of data types  
        class Check < UnknowDataType >  
        {  
            // Gerefic function to compare all data types  
            public bool Compare(UnknowDataType var1, UnknowDataType var2)  
            {  
                if (var1.Equals(var2))  
                {  
                    return true;  
                }  
                else  
                {  
                    return false;  
                }  
            }  
        }  
    }  
}

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). 

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
namespace GenericCollectionSample  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            // index based generic collection (arraylist)  
            List < int > listObj = new List < int > ();  
            listObj.Add(123);  
            listObj.Add(235);  
            // Displaying list value using index  
            Console.WriteLine("List Second Value: {0}", listObj[1]);  
            // Key based generic Collection (Dictionary)  
            Dictionary < int, string > objDic = new Dictionary < int, string > ();  
            objDic.Add(123, "Ramakrishna");  
            // Displaying Dictionary value using Key  
            Console.WriteLine("Dictionary Value: {0}", objDic[123]);  
            // Priority based Generic Collection (Stack)  
            Stack < int > objStack = new Stack < int > ();  
            objStack.Push(1);  
            objStack.Push(2);  
            objStack.Push(3);  
            // Display first value from Stack  
            Console.WriteLine("First Get Value from Stack: {0}", objStack.Pop());  
            // Priority based Generic Collection (Queues)  
            Queue < int > objQueue = new Queue < int > ();  
            objQueue.Enqueue(1);  
            objQueue.Enqueue(2);  
            objQueue.Enqueue(3);  
            // Display first value from Stack  
            Console.WriteLine("First Get Value from Queue: {0}", objQueue.Dequeue());  
            Console.WriteLine();  
            // Creating Employee records  
            Employee empObj1 = new Employee();  
            empObj1.ID = 1001;  
            empObj1.Name = "Ramakrishna";  
            empObj1.Address = "Hyderabad";  
            Employee empObj2 = new Employee();  
            empObj2.ID = 1002;  
            empObj2.Name = "Praveenkumar";  
            empObj2.Address = "Hyderabad";  
            // Creating generic List with Employee records  
            List < Employee > empListObj = new List < Employee > ();  
            empListObj.Add(empObj1);  
            empListObj.Add(empObj2);  
            // Displaying employee records from list collection  
            foreach(Employee emp in empListObj)  
            {  
                Console.WriteLine(emp.ID);  
                Console.WriteLine(emp.Name);  
                Console.WriteLine(emp.Address);  
                Console.WriteLine();  
            }  
            Console.Read();  
        }  
        public class Employee  
        {  
            public int ID;  
            public string Name;  
            public string Address;  
        }  
    }  
} 

Output

Output


Recommended Free Ebook
Similar Articles