I know that the += operator will add a method to the invocation list maintained by the Delegate base object, for example
using System;
class Program
{
delegate void MyDelegate(int n);
void Foo(int n)
{
Console.WriteLine("n = {0}", n)
}
static void Main(string[] args)
{
MyDelegate d = new MyDelegate(Foo);
d += Foo; // add Foo again
d.Invoke(3); // Foo is invoked twice as Foo appears two times in invocation list
}
}
But when I look at MSDN Delegate, MulticastDelegate I can't find any definition of the += operator. How is it that is just works? Auto-generated compiler magic?
It's not an operator on the delegate type itself, in IL terms - it's defined in the language specification, but you wouldn't find it using reflection. The compiler turns it into a call to
Delegate.Combine
. The reverse operation, using-
or-=
, usesDelegate.Remove
.At least, that's how it's implemented when C# targets .NET, as it almost always does. In theory, this is environment-specific - the language specification doesn't require that a compiler uses
Delegate.Combine
orDelegate.Remove
, and a different environment may not have those methods.From the C# 5 specification, section 7.8.4 (addition):
It's the same as with
Int32
,String
etc. The+
operator is defined implicitly by the language.You can check the source code of
Delegate
,MulticastDelegate
,Int32
etc. There are no overloads ofoperator +
there, that's why it doesn't appear in the MSDN documentation.From C# language spec, section 7.8.4:
There is a difference between simple types and delegates. The C# language specification doesn't require that a delegate is implemented using
System.Delegate
Note that there is no mention of
System.Delegate
there. Compare it with Section 4.1.4 Simple types:Or Section 4.2.4 The string type
So resolving the + operator for delegates to
Delegate.Combine
is an implementation detail of C# compilers in .NET framework.