Search code examples
c#delegatesmulticastdelegate

C# Delegate -- How to Bind a Delegate with multiple functions with different parameters first (same type) and then Fire/Invoke them later?


I need a C# Delegate to bind with multiple functions with different parameters first (same type) and then Fire/Invoke them later.

Please see my example below :

(Please note that my actual requirement is a lot more complex , but the same principle applies -- Don't want to bother you with the business/domain/implementation/boring bits). (Also , pardon the syntax , if its incorrect somewhere :P )

Suppose I have the following 4 functions , with the same type and number of parameters :

Void Add(int , int)
Void Subtract(int , int)
Void Multiply(int, int)
Void Divide(int , int)

I know Since they have the same parameters , I can have 1 delegate to point to all of the , correct ?

AND I Know that if i Use a multicast delegate , then I can use it to trigger all or some of them , right ?

For e.g. ,

delegate void MyDelegate (int a , int b);

And then use the delegate , something like this :-

MyDelegate del;


del = Add;

del += Subtract;
del += Multiply;

And later , I can use it like this :

del(10,20);

Now , this will fire all the functions with the same parameters 10 and 20.

My requirement is to have a multi cast delegate , where I can add up all the functions I want , but have different parameters for them.

They should not be fired/invoked when I specify the parameters, instead , they should be invoked/fired later , but altogether , and in the order then I chained/linked them.

For e.g : I want to do something like this :

delayedDelegate = Add(1,2);
//
//Some Code Here
//
delayedDelegate += Subract(3,4)

//
//Some More Code Here
//

delayedDelegate += Multiply(5,6)

//
//More Code Here
//


delayedDelegate += Add(7,8);

//
// Just a little More Code Here
//

Finally , get down to the execution :

// Fire all the chained functions with the parameters that werer assigned to them.
delayedDelegate.Invoke();     

I remember i read something of this sort , but just cant find anything by googling today. Any help would be gladly appreciated.


Solution

  • The simplest solution I can think of is to use lambda expression to create closure that "converts" delegate with arbitrary parameters values to parameterless Action delegates. Add as many delegates as you want and then call them at once like this:

        //convert each delegate with parameters to Action
        Action delayedDelegate = () => Add(1, 2);
        delayedDelegate += () => Subtract(3, 4);
        delayedDelegate += () => Multiply(5, 6);
    
        //Later call all delegates at once
        delayedDelegate();