6

I see the equality comparison operators == and != overloaded on System.Delegate and MulticastDelegate but not the += and -= operators.

Then how do the increment assign and decrement assign operators work on delegate instances?

1

4 Answers 4

7

The C# compiler translates += operator to the call of the static method Delegate.Combine.

There are several cases when the compiler does such things, f.e. the + operator of the System.String is compiled to the String.Concat call. Therefore there isn't op_Add method in System.String.

1

The addition operator and the compound assignment(+=) operator of delegates are both built-in supported by the c# compiler.As the 'C# Language Specification' says:

Delegate combination. Every delegate type implicitly provides the following predefined operator, where D is the delegate type: D operator +(D x, D y); The binary + operator performs delegate combination when both operands are of some delegate type D. (If the operands have different delegate types, a binding-time error occurs.) If the first operand is null, the result of the operation is the value of the second operand (even if that is also null). Otherwise, if the second operand is null, then the result of the operation is the value of the first operand. Otherwise, the result of the operation is a new delegate instance that, when invoked, invokes the first operand and then invokes the second operand. For examples of delegate combination, see §7.8.5 and §15.4. Since System.Delegate is not a delegate type, operator + is not defined for it.

1
0

The += operator is inferred from the + operator.

See += Operator (C# Reference)

2
  • Good point, but I don't see even the addition or subtraction operators in the classes. Feb 8, 2015 at 6:58
  • @WaterCoolerv2: delegate types, like array types, are a little "different", in that the runtime automatically generates a variety of members. You won't see them in the class library docs. Feb 8, 2015 at 6:59
0

When you declare a delegate as an event, it is actually an event wrapper around the delegate. See https://stackoverflow.com/a/4893006/397807 for the details. In short, you can only add a handler with += and remove with -= and compiler will help translate it to proper function call.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.