Generic Classes in C#

Generic Class

Let us have a look at the Generic class in C#. Generic classes in C# have type parameters. The generic class introduces a type parameter. This becomes part of the class definition itself. The generic class of Type T is used in the following demo. The letter T denotes a type that is only known based on the calling location.

Open Visual Studio. Select the project type as console application.

Step 1

Click on File -> New -> Project.

create project

Step 2

Select Visual C# from left the hand pane. Choose Console Application in the right side. Name the Project “Generic Class”. Define the desired location to save the project in your hard drive. Click OK.

console application

Step 3

Write the following code in the application.

  1. public class Myclass<T>  
  2. {  
  3.     public void Compareme(T v1, T v2)  
  4.     {  
  5.         if (v1.Equals(v2))  
  6.         {  
  7.             Console.Write("The value is matching");  
  8.         }  
  9.         else  
  10.         {  
  11.             Console.Write("The value is not matching");  
  12.         }  
  13.     }  
  14. }  
  15.   
  16. class Program  
  17. {  
  18.     static void Main(string[] args)  
  19.     {  
  20.         Myclass<string> objmyint = new Myclass<string>();  
  21.         objmyint.Compareme("Amit","Amit");  
  22.         Console.ReadLine();  
  23.   
  24.     }  
  25. }  

When we run the preceding code we get the following output.

value matching

Let us now change the string to something else and check the output. In this scenario I have made my second string parameter “amit”.

  1. public class Myclass<T>  
  2. {  
  3.     public void Compareme(T v1, T v2)  
  4.     {  
  5.         if (v1.Equals(v2))  
  6.         {  
  7.             Console.Write("The value is matching");  
  8.         }  
  9.         else  
  10.         {  
  11.             Console.Write("The value is not matching");  
  12.         }  
  13.     }  
  14. }  
  15.   
  16. class Program  
  17. {  
  18.     static void Main(string[] args)  
  19.     {  
  20.         Myclass<string> objmyint = new Myclass<string>();  
  21.         objmyint.Compareme("Amit","amit");  
  22.         Console.ReadLine();  
  23.   
  24.     }  
  25. }  

Let us see the output now.

value not matching


Similar Articles