Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I see the += operator overloaded on System.Delegate?

Tags:

c#

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?

like image 544
Water Cooler v2 Avatar asked Feb 08 '15 06:02

Water Cooler v2


2 Answers

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.

like image 114
Mark Shevchenko Avatar answered Nov 03 '22 01:11

Mark Shevchenko


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.

like image 42
jatom Avatar answered Nov 02 '22 23:11

jatom