Knowledge Management Banner

Knowledge Management Banner

C# : Generics : Part 24

Generics
  • Generics heps us to write class or method that can work with any data type
  • It helps to maximize code reuse, type safety and performance.
  • In code below you can see that string type is passed to the method which is received as object where value type is converted to reference type. which result in boxing and degrading the performance
  •  namespace Generics  
     {  
       class Program  
       {  
         static void Main(string[] args)  
         {  
           var result = Compare(23, 22);  
         }  
         public static bool Compare(object a, object b)  
         {  
           return a.Equals(b);  
         }  
       }  
     }  
    

  • Hence to avoid boxing and unboxing as shown in above code Generics are to be used, Which is shown in example below.
  •  namespace Generics  
     {  
       class Program  
       {  
         static void Main(string[] args)  
         {  
           var result = Compare<int>(23, 22);  
         }  
         public static bool Compare<T>(T a, T b)  
         {  
           return a.Equals(b);  
         }  
       }  
     }  
    

No comments

Powered by Blogger.