How to combine delegates in C #

I want to implement a method that accepts two delegates Action A1 and Action A2 and returns a new delegate that combines them. The signature of his method is as follows:

public static Action<Tuple<T1,T2>> CombineWith<T1,T2>(this Action<T1> a1, Action<T2> a2) 

So instead of talking

 { A1(t1); A2(t2); } 

I want to write:

 { A1.CombineWith(A2)(Tuple.Create(t1,t2)); } 

What is the possible implementation of this method maybe?

+7
source share
1 answer

I think you want:

 public static Action<Tuple<T1,T2>> CombineWith<T1,T2> (this Action<T1> action1, Action<T2> action2) { //null-checks here. return tuple => { action1(tuple.Item1); action2(tuple.Item2); }; } 

Using:

 Action<int> a1 = x => Console.Write(x + 1); Action<string> a2 = x => Console.Write(" " + x + " a week"); var combined = a1.CombineWith(a2); // output: 8 days a week combined(Tuple.Create(7, "days")); 

EDIT : By the way, I noticed that you mentioned in a comment that "accepting arguments individually would be even more preferable." In this case, you can:

 public static Action<T1, T2> CombineWith<T1, T2> (this Action<T1> action1, Action<T2> action2) { //null-checks here. return (x, y) => { action1(x); action2(y); }; } 
+15
source

All Articles