I want to implement a method which takes two Action A1 and Action A2 delegates and returns new delegate, which combines them. The signature of he method is the following:
public static Action<Tuple<T1,T2>> CombineWith<T1,T2>(this Action<T1> a1, Action<T2> a2)
So, instead of saying
{
A1(t1);
A2(t2);
}
I want to be able to write:
{
A1.CombineWith(A2)(Tuple.Create(t1,t2));
}
What is the possible implementation of this method can be?
Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.
The multicast delegate contains a list of the assigned delegates. When the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same type can be combined. The - operator can be used to remove a component delegate from a multicast delegate.
A delegate is a type safe and object oriented object that can point to another method or multiple methods which can then be invoked later. It is a reference type variable that refers to methods.
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);
};
}
Usage:
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 you mentioned in a comment that "taking arguments individually would be even more preferable". In that case, you can do:
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); };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With