0

I have a method that I want to use as a callback. Lets say its the following:

public void TestCallback(int a, int b)
{ 
    Console.WriteLine(a + b);
}

Now let's say that I want to pass this as a parameter to another method that takes a delegate matching TestCallback's signature.

public void TestMethodA(Action<int, int> paramFunc)
{
    TestMethodB(paramFunc);
}

In turn, let's say TestMethodA passes this delegate to another function, which finally invokes it:

public void TestMethodB(Action<int, int> paramFunc)
{
    paramFunc.Invoke(5, 10);
}

Now what if I wanted to pass another parameter from TestMethodA to TestMethodB` which will finally be used as a parameter for the delegate. Would the best approach to do this be like this:

public void Main(string[] args)
{
    TestMethodA(TestCallback);
}

public void TestMethodA(Action<int, int> paramFunc)
{
    TestMethodB(paramFunc, 10);
}

public void TestMethodB(Action<int, int> paramFunc, int paramForDelegate)
{
    paramFunc.Invoke(5, paramForDelegate);
}

Or like this:

public void Main(string[] args)
{
    TestMethodA(TestCallback);
}

public void TestMethodA(Action<int, int> paramFunc)
{
    TestMethodB((a, b) => paramFunc(a, 10));
}

public void TestMethodB(Action<int, int> paramFunc)
{
    paramFunc.Invoke(5, 20); // 20 here is just a placeholder and will not be passed to the delegate
}

Using the first approach, the methods signatures need to carry all the parameters to be used in the delegate. If for example I had more parameters to pass and there were more chained calls, you can imagine how this would become ugly quickly.

Using the second approach keeps the method signatures cleaner, but I think it also makes the code harder to decipher, and I am forced to invoke my delegate with a parameter that will not actually be passed to it.

Is there a better approach to achieving what I described? That is, passing a delegate and also some parameters to be passed to it when invoked?

  • Second approach looks weird, but a similar approach called currying is well used https://stackoverflow.com/questions/411572/proper-currying-in-c-sharp – Charlieface Feb 28 '21 at 13:44
  • _"better"_ is subjective, which means off-topic and unsuitable for Stack Overflow. See duplicate for existing question that already discusses the basic technique. – Peter Duniho Feb 28 '21 at 18:29

0 Answers0