0

I have a multicast delegate question.

This is based on some code in C# In A Nutshell Version 5.

using System;
using System.Collections;
using System.Collections.Generic;

public delegate int Transformer(int x);

class MainClass
{
    static int Square(int x) { return x * x; }
    static int Cube(int x) { return x * x * x; }

    static void Main()
    {
        Transformer t, q, multi;
        t = Square;
        q = Cube;

        multi = t + q;
        for (int i = 1; i < 5; i++)
            Console.WriteLine(multi(i));
    }
}

The output is from Cube alone. Why does the addition fail?

1
  • Wrong operator, you meant to use t(i) + q(i). The C# compiler makes hay of your current code by calling Delegate.Combine(). Giving you a new delegate object that calls both targets, one after another. The result is whatever is returned by the last target. Commented Nov 20, 2014 at 16:06

1 Answer 1

1

First the Square method runs and then the Cube method runs for each value. The return value of multi() is the return value of last method in the invocation list, so that's why you see only the value of Cubes.

The addition does not faill it works as expected. You can verify this by putting a Console.WriteLine inside of the Square method.

Sign up to request clarification or add additional context in comments.

1 Comment

@Ron That's almost certainly not the proper design here. You should simply apply a collection of delegates, rather than a single delegate with multiple associated methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.