C# Generic Method

Generic Method:

C# also provides Generic Methods. We can create a method which defer the parameter data type until the method is called. These parameters are called Type parameters that means we can pass the actual data type later.
In that method we have declared a Type argument after the method name <T>. T is the type argument.

Code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace genericMethod  
  8. {  
  9.     class Program  
  10.     {  
  11.   
  12.         public static void compareTo<T>(T a, T b)  
  13.         {  
  14.             if (a.Equals(b))  
  15.                 Console.WriteLine("True");  
  16.             else  
  17.                 Console.WriteLine("False");  
  18.         }  
  19.   
  20.         static void Main(string[] args)  
  21.         {  
  22.             compareTo<int>(12, 12);  
  23.             compareTo<int>(12, 11);  
  24.             compareTo<float>(12.45f, 11.45f);  
  25.             compareTo<string>("Sujan","Sujan");  
  26.             Console.ReadKey();  
  27.         }  
  28.     }  
  29. }  
Share:

0 Comments:

Post a Comment