Assume you want to define a delegate type that can call any method returning void and receiving a single parameter.


public delegate void MyGenericDelegate<T>(T arg);
 
MyGenericDelegate<string> strTarget = new MyGenericDelegate<string>(StringTarget);
MyGenericDelegate<int> intTarget = new MyGenericDelegate<int>(IntTarget);
strTarget("Some string Data");
intTarget(9);
 
private static void IntTarget(int arg)
 {
     Console.WriteLine(arg);
 }
private static void StringTarget(string arg)
 {
     Console.WriteLine(arg.ToUpper());
 }


The Generic Action<> and Func<> Delegates

In many cases, you simply want "some delegate" that takes a set of arguments and possibly has a return value other than void.


The generic Action<> delegate is defined in the System namespace, and you can use this generic delegate to "point to" a method that takes up to 16 arguments and returns void.


// This is a target for the Action<> delegate
static void DisplayMessage(string msg,ConsoleColor txtColor,int printCount)
 {
     Console.ForegroundColor = txtColor;
     for(int i = 0; i < printCount; i++)
     {
         Console.WriteLine(msg);
     }
 }
 
Action<string, ConsoleColor, int> actionTarget = DisplayMessage;
actionTarget("Action message", ConsoleColor.Yellow, 5);


The generic Func<> delegate can point to methods that (like Action<>) take up to 16 parameters and a custom return value.


// Target for the Func<> delegate
static int Add(int x, int y)
 {
     return x + y; 
 }
 
Func<int, int, int> funcTarget = Add;
int result = funcTarget.Invoke(40, 40);
Console.WriteLine(result);