Multicasting of a Delegate wrong answer

42 views Asked by At

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

There are 1 answers

0
Sweeper On

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