ReSharper 2016.1 Help

Code Inspection: Delegate subtractions

The .NET framework defines operator overloads for the + and - operators on the Delegate data type. The + operator effectively combines delegates so that a multiple delegates are called within one. The - operator, on the other hand, attempts to remove the delegate invocation list from a delegate.

The list distinction is important here: what this implies is that subtraction of a delegate effectively implies a subtraction of lists. For example, in the code below, removing the A and C delegates from the ABC invocation list via the expression s - (a + c) has no effect whatsoever, because AC is not a sublist of ABC.

static void Main() { Action a = () => Console.Write("A"); Action b = () => Console.Write("B"); Action c = () => Console.Write("C"); Action s = a + b + c + Console.WriteLine; s(); //ABC (s - a)(); //BC (s - b)(); //AC (s - c)(); //AB (s - (a + b))(); //C (s - (b + c))(); //A (s - (a + c))(); //ABC }

It is also worth noting that sublist removal happens from the end of the list. For example:

s = a + b + a; (s - a)(); // AB

Since the above mechanics can lead to unpredictable results, ReSharper issues a warning whenever it encounters a delegate subtraction operator.

See Also

Last modified: 19 August 2016