Generics In C# and .NET

What are Generics in C# and .NET?

Generics were introduced in C# version 2.0. Generics allows us to make a class or a method, which are independent of its datatype. Generics are extensively used by the collection classes, which are present in system.collections.Generic namespace.

Features of Generics

  • It helps you to maximize the code reuse.
  • Makes the method strongly typed and increases the performance.
  • We can create our own Generic interfaces, classes, methods and Delegates.
  • You may get the information on the types, which are used in a Generic datatype in runtime by means of reflection.

Sample program using Generics 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Collections;  
  4. using System.Linq;  
  5. using System.Text;  
  6. namespace GenericExample {  
  7.     public class Program {  
  8.         static void Main() {  
  9.             bool Result = StrinComparison.CompareString < string > ("sainath""sainath");  
  10.             Console.WriteLine(Result);  
  11.             Console.ReadLine();  
  12.         }  
  13.     }  
  14.     public class StrinComparison {  
  15.         public static bool CompareString < T > (T FirstString, T SeconString) {  
  16.             return FirstString.Equals(SeconString);  
  17.         }  
  18.     }  
  19. }   

In the program given above, you can see that I have compared two strings. Using Generics “T” which means type in the place of T, you can compare the two numbers or the two characters making the method independent of its datatype.