0

I want to make connections between those functions.

public delegate double Math_calculation(double num);
static double z = 6;
static void Main(string[] args)
{
  Math_calculation math ;
  Math_calculation math1 = cube, math2 = root, math3 = half;
            
  math = math1;
  math += math2;
  math += math3;
  Console.WriteLine($"solution={math(z)}");
}
public static double root(double x) => z=Math.Sqrt(x);
public static double cube(double x) => z=Math.Pow(x, 3);
public static double half(double x) => z= x / 2;

Exactly output:3
Expected output:7.34...(sqrt(216)/2)

  • 1
    No, multicast delegates are not function composition. – Sweeper Jun 24 '22 at 08:51
  • @Charlieface I don't think it does. OP seems to be trying to compose the invocation list of a multicast delegate, which is an interesting problem that I've never seen before. – Sweeper Jun 24 '22 at 09:11
  • 1
    @Sweeper Given a list of `Func` you can very easily execute them one by one. `result = startValue; foreach (var func in list) result = func(result);`. I'm sure there must be a dupe somewhere – Charlieface Jun 24 '22 at 09:13
  • ok I know how modify my program, change the above method x to z ex:z=Math.sqrt(z) or pass ref x as parameter – Jr. dective Jun 24 '22 at 09:39

1 Answers1

0

The return value of a multicast delegate is the return value of the last member in its invocation list. It is not the function composition that you expect. Every method in the invocation list is invoked with the same z argument. (See also this post)

You would have to do the function composition yourself. For example, like this:

var composedDelegate = math.GetInvocationList().Aggregate((del1, del2) => 
    new Math_calculation(x => (double)del2.DynamicInvoke(del1.DynamicInvoke(x)))
);

Note that in this way you end up with a "single-cast" delegate that you can use:

Console.WriteLine(((Math_calculation)composedDelegate)(z));
// or
Console.WriteLine(composedDelegate.DynamicInvoke(z));
Sweeper
  • 213,210
  • 22
  • 193
  • 313