Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 297
Peter17 Avatar asked Feb 23 '11 08:02

Peter17


People also ask

Can delegates be chained together C#?

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.

What is multi cast delegates?

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.

Can a delegate point to more than 1 method?

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.


1 Answers

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); };
}
like image 122
Ani Avatar answered Sep 24 '22 12:09

Ani