Generic Delegates in C#

Before you continue reading this article, you must be familiar with the basics of delegates in C#. If you do not understand delegates then I highly recommend reading this previous article on Delegates.  
In the preceding article and code sample, we have a delegate called DelegateInt that takes two integer parameters and returns an int type. 
  1. public delegate int DelegateInt(int a, int b);  

The DelegateInt works only with methods that have two integer parameters. What if we want to create a delegate that will work with any type of two parameters and return any type? In that case, it will not work. This is where generics are useful and generics play a major role in LINQ.

The following code snippet declares a generic delegate. 

  1. public delegate string GenericDelegateNumber<T1, T2>(T1 a, T2 b);  

The following code snippet defines two methods for creating instances of generic delegates. 

  1. public static string AddDoubles(double a, double b)  
  2. {  
  3.   return (a + b).ToString();  
  4. }  
  5.   
  6. public static string AddInt(int a, int b)  
  7. {  
  8.   return (a + b).ToString();  
  9. }  

The following code snippet creates two delegate instances where the first one uses integers and the second delegate uses double parameter values. 

  1. GenericDelegateNumber<intint> gdInt = new GenericDelegateNumber<intint>(AddInt);  
  2. Console.WriteLine(gdInt(3, 6));  
  3. GenericDelegateNumber<doubledouble> gdDouble = new GenericDelegateNumber<doubledouble>(AddDoubles);  
  4. Console.WriteLine(gdDouble(3.2, 6.9));  

The following code lists the complete sample. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace GenericDelegateSample  
  8. {  
  9. class Program  
  10. {  
  11. static void Main(string[] args)  
  12. {  
  13. GenericDelegateNumber<intint> gdInt = new GenericDelegateNumber<intint>(AddInt);  
  14. Console.WriteLine(gdInt(3, 6));  
  15. GenericDelegateNumber<doubledouble> gdDouble = new GenericDelegateNumber<doubledouble>(AddDoubles);  
  16. Console.WriteLine(gdDouble(3.2, 6.9));  
  17. Console.ReadKey();  
  18. }  
  19.   
  20. // Generic Delegate takes generic types and returns a string  
  21. public delegate string GenericDelegateNumber<T1, T2>(T1 a, T2 b);  
  22.   
  23. public static string AddDoubles(double a, double b)  
  24. {  
  25. return (a + b).ToString();    
  26. }  
  27.   
  28. public static string AddInt(int a, int b)  
  29. {    
  30. return (a + b).ToString();    
  31. }  
  32. }  
  33.   
  34. }  

 

 

Up Next
    Ebook Download
    View all
    FileInfo in C#
    Read by 9.7k people
    Download Now!
    Learn
    View all