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. 

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. 

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

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

public static string AddDoubles(double a, double b)  
{  
  return (a + b).ToString();  
}  
  
public static string AddInt(int a, int b)  
{  
  return (a + b).ToString();  
}

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

GenericDelegateNumber<int, int> gdInt = new GenericDelegateNumber<int, int>(AddInt);  
Console.WriteLine(gdInt(3, 6));  
GenericDelegateNumber<double, double> gdDouble = new GenericDelegateNumber<double, double>(AddDoubles);  
Console.WriteLine(gdDouble(3.2, 6.9));

The following code lists the complete sample. 

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
  
namespace GenericDelegateSample  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            GenericDelegateNumber<int, int> gdInt = new GenericDelegateNumber<int, int>(AddInt);  
            Console.WriteLine(gdInt(3, 6));  
            GenericDelegateNumber<double, double> gdDouble = new GenericDelegateNumber<double, double>(AddDoubles);
            Console.WriteLine(gdDouble(3.2, 6.9));  
            Console.ReadKey();  
        }  
  
        // Generic Delegate takes generic types and returns a string  
        public delegate string GenericDelegateNumber<T1, T2>(T1 a, T2 b);  
  
        public static string AddDoubles(double a, double b)  
        {  
            return (a + b).ToString();    
        }  
  
        public static string AddInt(int a, int b)  
        {
            return (a + b).ToString();    
        }
    }
}


Recommended Free Ebook
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.