Generic Action Delegate

PHOTO EMBED

Mon Sep 20 2021 13:35:43 GMT+0000 (UTC)

Saved by @dejohnny #c

static void Main(string[] args)
{
    Action<int> firstAction = DoWorkWithOneParameter;
    Action<int, int> secondAction = DoWorkWithTwoParameters;
    Action<int, int, int> thirdAction = DoWorkWithThreeParameters;

    firstAction(1); // Print 1
    secondAction(1, 2); // Print 1-2
    thirdAction(1, 2, 3); //Print 1-2-3
}

public static void DoWorkWithOneParameter(int arg)
{
    Console.WriteLine(arg);
}

public static void DoWorkWithTwoParameters(int arg1, int arg2)
{
    Console.WriteLine(arg1 + "-" + arg2);
}

public static void DoWorkWithThreeParameters(int arg1, int arg2, int arg3)
{
    Console.WriteLine(arg1 + "-" + arg2 + "-" + arg3);
}
content_copyCOPY

We have to choose Action delegate according to the method, which we want to store. If our method takes two parameters, then we have to choose action delegate which has two parameters Action<in T1, T2>(T1 arg1, T2 arg2). Below are some examples