Roy Osherove

View Original

The problem with Multi-Cast Delegates

Here’s a very interesting situation you can get yourself into when working with delegates: you have a delegate that returns a result. You use this delegate as part of your calculation. What happens when you have multiple targets on the delegate, each returning a different result? Here’s code that demonstrates this:

Class1 has a calculation delegate that receiv different result? Here’s  code that demonstrates this:

Class1 has a calculation es 2 numbers and returns a result. It uses this delegate as part of some simple algorithm. The MyClient class attaches 2 different callbacks to the same delegate of Class1, each returning a different result.

What will be the result when MyClient actually calls the DoDelegateWork() function on Class1?

 

 

public delegate int CalculationDelegate(int num1,int num2);

public class Class1

{

      public CalculationDelegate DoCalculation;

      public int DoDelegateWork()

      {

            if(DoCalculation!=null)

            {

                  int result= DoCalculation(3,3);

                  return result;

            }

 

            return 0;

      }

}

 

public class MyClient

{

public void AttachToDelegate()

{

Class1 c = new Class1();

c.DoCalculation+=new CalculationDelegate(c_DoCalculation);

c.DoCalculation+=new CalculationDelegate(c_DoCalculation2);

}

 

private int c_DoCalculation(int num1, int num2)

{

      return num1*num2;

}

 

private int c_DoCalculation2(int num1, int num2)

{

      return num1+num2;

}

}

 

The answer is that whatever target in the invocation list was invoked last will be used to return the actual result. All the other results are discarded. Pretty crazy. It’s pretty weird that we are actually able to do something like this in the framework, and that there is no simple way to avoid this predicament. (I stress, no simple way. We can just through a few hoops to make sure this does not happen, but there is no built in support construct that will deny this from happening. This effect is caused by the fact that all delegates are actually Multicast Delegates.

 

(PS: this same code works just as well whether the delegate is declared as an event or not. Events were never meant to be used this way, but hey, it's good to know you can of you really need to in some twisted way!)