Reading the documentation I see that the + operator can be used to build / merge delegates of the same type.
In the same way, I see that I can remove a from the composite delegate using the - operator.
I also noticed that the Action type has static methods Combine and Remove , which can be used to combine the call lists of two delegates and to remove the last occurrence of the call list of the delegate from the call list of the other delegate, respectively.
Action a = () => Debug.WriteLine("Invoke a"); Action b = () => Debug.WriteLine("Invoke b"); a += b; a.Invoke(); //Invoke a //Invoke b Action c = () => Debug.WriteLine("Invoke c"); Action d = () => Debug.WriteLine("Invoke d"); Action e = Action.Combine(c, d); e.Invoke(); //Invoke c //Invoke d a -= b; a.Invoke(); //Invoke a e = Action.Remove(e, d); e.Invoke(); //Invoke c
They seem to give the same results in terms of how they are combined / removed from the call list.
I have seen both methods used in various examples on SO and in other code. Is there a reason why I should use one or the other? Are there any pits? For example, I see a warning at line a -= b; which states that Delegate subtraction has unpredictable results - so should I avoid this with Remove?
Fraser
source share