I couldn't find the + operator in Reflector under Delegate
or MulticastDelegate
.
I'm trying to figure out how this doesn't need a cast:
Action a = () => Console.WriteLine("A");
Action b = () => Console.WriteLine("B");
Action c = a + b;
But this does:
Action a = () => Console.WriteLine("A");
Action b = () => Console.WriteLine("B");
Action c = (Action)MulticastDelegate.Combine(a, b);
In the first sample is the cast just done under the covers?
Taking the following example:
Then looking at it with ILSpy:
Seems that they do the exact same thing, just C# is providing some syntactic sugar in the first test.
Yes, you can say that!
The
Combine
method was written in .NET 1 where no generic C# existed. The formal return type ofCombine
therefore had to beDelegate
:But the method still returns an
Action
when botha
andb
areAction
. And yes,a
andb
are required to have the same runtime type.Please don't write
MulticastDelegate.Combine
asCombine
is astatic
method defined by theSystem.Delegate
class. Therefore sayDelegate.Combine
, that's less confusing.Detour:
The current version of C# and
Combine
has problems with contravariant delegate types. Consider the following:Now, suppose some future version of the framework introduced a generic
Combine
method:and suppose C# was changed such that
+
was translated into a call to the new genericCombine<>
method, then contravariance and delegate combination would be fixed! I guess they tell us they have higher priorities, but still.Its done using "operator overloading", you can do this in your own objects aswell.
Result: o3.Property = "Hello World!"
So I assume the framwork performs somthing like this in the background
+=
and-=
is implemented at the language level (i.e. with compiler help) with known delegate types, so it doesn't need a cast, whereasDelegate.Combine
is just an ordinary (non-generic) method withDelegate
return type, so it needs a cast.