Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composing multicast delegates in C# - should I use operators or Action.Combine?

Reading the documentation I can see that + operator can be used to compose/combine delegates of the same type.

In the same way I can see that I can remove a from the composed delegate using the - operator.

I also noticed that the Action type has static Combine and Remove methods that can be used to concatenate the invocation lists of two delegates, and to remove the last occurrence of the invocation list of a delegate from the invocation list of another 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 appear to produce the same results in terms of how they combine/remove from the invocation list.

I have seen both ways used in various examples on SO and in other code. Is there a reason that I should be using one way or the other? Are there any pit falls? For example - I can see a warning in the line a -= b; stating that Delegate subtraction has unpredictable results - so should I avoid this by using Remove?

like image 201
Fraser Avatar asked Jan 07 '13 14:01

Fraser


1 Answers

The delegate operators (+ and -) are shorthand for the static methods.
There is no difference at all.

a += b compiles to a = (Action)Delegate.Combine(a, b)

like image 173
SLaks Avatar answered Oct 30 '22 11:10

SLaks