Peter17
Peter17

Reputation: 3092

How to combine delegates in C#

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?

Upvotes: 7

Views: 2322

Answers (1)

Ani
Ani

Reputation: 113462

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); };
}

Upvotes: 15

Related Questions