Multicast Delegate Ambigous

166 views Asked by At

I have below code

    StringOperations sumString, reverseString, lowerString, upperString, multicastString;

    sumString = new StringOperations(sum);
    reverseString = new StringOperations(reverse);
    lowerString = new StringOperations(lower);
    upperString = new StringOperations(upper);

    multicastString = upperString + lowerString + reverseString + sumString;

    int count = 4;

    if (!checkBox1.Checked)
    {
            multicastString -= upperString;
            count--;
    }
    if (!checkBox2.Checked)
    {
            multicastString -= reverseString;
            count--;
    }
    if (!checkBox3.Checked)
    {
            multicastString -= lowerString;
            count--;
    }
    if (!checkBox4.Checked)
    {
            multicastString -= sumString;
            count--;
    }
    if (count > 0)
    {
            string test = multicastString(textBox1.Text);
    }

When uppercase and lowercase checkboxes are selected then it only show me lowercase function's result.

If I select uppercase, lowercase and reverse checkboxes then it only show me result of reverse function.

My delegate is below

delegate string StringOperations(string str);

I am using multicast delegate and returning string as shown in above code. Please let me know what I am doing wrong?

2

There are 2 answers

4
Sami Kuhmonen On BEST ANSWER

When you have a delegate that has multiple handlers attached to it, you will still get only one return value. There is no direct way to get the other values and naturally you cannot chain the handler functions in a way that the return value of one would be sent to another. The only thing you will get is the last attached handler's return value is returned.

There is no ambiguous behaviour here really, it's just the way it works. If you want to chain the functions you have to use a different approach then a delegate. In this example you could just call the functions and that's it.

0
Junaid S. On

In multicast delegate, methods should have void as return type because it will not mix the values. So method signature will change

from

delegate string StringOperations(string str);

to

delegate void StringOperations(string str);

PS: Also change the return type of other delegated methods to void.