-2

I found a possible scenario w.r.t. MultiCast Delegates which I am not able to get around. I am not able to assign multiple methods to a Delegate object in the Main class. Only the last method is getting registered with the delegate. In this case, it's the Subtract() method. Is there a restriction around that which I am not aware of?

static void Main(string[] args)
{
    Calculator calc = new Calculator();
    //Create a Delegate object
    CalcDelegate delObj, delObj2, delObj3, delObj4;
    CalcDelegate delObj5 = null;
    //Register methods with delegate objects
    delObj = new CalcDelegate(calc.Add);
    delObj2 = new CalcDelegate(calc.Subtract);
    delObj3 = (CalcDelegate)Delegate.Combine(delObj, delObj2);
    Console.WriteLine(delObj3.Method);

    delObj4 = delObj + delObj2;
    Console.WriteLine(delObj3(40, 20));
    Console.WriteLine(delObj4(40, 20));

    delObj5 += calc.Add;
    delObj5 += calc.Subtract;
    Console.WriteLine(delObj5(40, 20));
    Console.ReadKey();
}

Here's my implementation of the Calculator class along with the delegate:

public delegate int CalcDelegate(int a, int b);
public class Calculator
{
    public int Add(int x, int y)
    {
        return x + y;
    }

    public int Subtract(int x, int y)
    {
        return x - y;
    }
}
Servy
  • 202,030
  • 26
  • 332
  • 449
Mohit632
  • 1
  • 2
  • Sorry, I searched for the answer but could not find an appropriate one. Thanks for sharing the link. – Mohit632 Mar 16 '18 at 04:46

1 Answers1

0

All methods are assigned, delegates return the result from the last method from the methods' chain since there are multiple results, but delegate can return only one value. Add Console.WriteLine to both Add and Subtract and you will see that both of them are invoked.

Alex Sikilinda
  • 2,928
  • 18
  • 34
  • Thanks @Alex. So as all the methods are subscribed and have been called, since the functions are returning an int value it makes sense to return the value from last function. Just didn't think in that direction. – Mohit632 Mar 16 '18 at 04:49