C# Generic Class

Generic Class:

Generics allow you to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific type at compile time.
A generic class can be defined using angle brackets <>. For example, the following is a simple generic class with a generic member variable, generic method and property.
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 genericClass  
  8. {  
  9.     class genericDemo  
  10.     {  
  11.         public void add<T>(T a, T b)  
  12.         {  
  13.             dynamic d1 = a; //Dynamic define type in run time.......  
  14.             dynamic d2 = b;  
  15.             Console.WriteLine(d1+d2);  
  16.         }  
  17.   
  18.         public void sub<T>(T a, T b)  
  19.         {  
  20.             dynamic d1 = a;  
  21.             dynamic d2 = b;  
  22.             Console.WriteLine(d1 - d2);  
  23.         }  
  24.   
  25.         public void mul<T>(T a, T b)  
  26.         {  
  27.             dynamic d1 = a;  
  28.             dynamic d2 = b;  
  29.             Console.WriteLine(d1 * d2);  
  30.         }  
  31.   
  32.         public void div<T>(T a, T b)  
  33.         {  
  34.             dynamic d1 = a;  
  35.             dynamic d2 = b;  
  36.             Console.WriteLine(d1 / d2);  
  37.         }  
  38.     }  
  39. }  
  40.   
  41. //Main class....  
  42.   
  43. using System;  
  44. using System.Collections.Generic;  
  45. using System.Linq;  
  46. using System.Text;  
  47. using System.Threading.Tasks;  
  48.   
  49. namespace genericClass  
  50. {  
  51.     class Program  
  52.     {  
  53.   
  54.         static void Main(string[] args)  
  55.         {  
  56.               
  57.             genericDemo gDemo = new genericDemo();  
  58.   
  59.             gDemo.add<int>(11,11);  
  60.             gDemo.add<double>(11.45, 12.33);  
  61.             gDemo.sub<int>(12, 7);  
  62.             gDemo.mul<double>(11.45, 12.77);  
  63.             gDemo.div<int>(33, 12);  
  64.             gDemo.add<string>("Sujan","Hasan");  
  65.   
  66.             Console.ReadKey();  
  67.         }  
  68.     }  
  69. }  
Share:

0 Comments:

Post a Comment