Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compose two lambdas of type "delegate" in c#

Lets assume we have defined two Lambdas.

Func<TInput, TOutput> a = …;
Func<TInput1, TInput2, TOutput> b = …;

Now lets assume that we have some code that does not work with generics and receives these Lambdas as not further typed delegates.

delegate da = a;
delegate db = b;

In that code, we want to compose the two lambdas / delegates to a new, composed lambda e.g. (i1, i2) => b(a(i1), i2), but a and b are not accessible, only da and db are accessible. How can this be done in an elegant way?

like image 389
Philipp Kramer Avatar asked Jan 01 '26 07:01

Philipp Kramer


1 Answers

Does this what you want?:

Func<int, int> a = p0 => p0 << 1;
Func<int, int, int> b = (p0, p1) => p0 + p1;

Delegate da = a;
Delegate db = b;

var inner = da.Method.GetParameters().Length < db.Method.GetParameters().Length ? da : db;
var outer = inner == da ? db : da;

Func<int, int, int> c = (i1, i2) => (int)outer.DynamicInvoke(inner.DynamicInvoke(i1), i2);

I would prefer to create an expression tree to build a new lambda that's created as you want. Maybe there is more logic needed to determine which argument should be passed to a and at which parameter the result of a is passed to b.

Is that the way you want to go?

like image 154
Sebastian Schumann Avatar answered Jan 03 '26 19:01

Sebastian Schumann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!