10

If I create a delegate in my code like :

delegate void dostuff (string o);

This generates a class that derives from System.MulticastDelegate which implements three methods - Invoke, BeginInvoke and EndInvoke.

If I look at the compiled IL for Invoke all I see is :

.method public hidebysig newslot virtual 
        instance void  Invoke(string o) runtime managed
{
} // end of method dostuff::Invoke

The method contains no code. Calling it does work - the delegate gets invoked, but I can't see how it does it.

Where does the voodoo that makes calling Invoke actually call the delegate come from?

Warren Rumak
  • 3,824
  • 22
  • 30
Mongus Pong
  • 11,337
  • 9
  • 44
  • 72
  • It's just part of the underlying .Net framework -- the call *is* the call to invoke. `MyDelegate.Invoke()` is the same as `MyDelegate()` – Iain Ballard Jun 17 '11 at 16:03
  • MyDelegate() is just syntactic sugar that gets compiled down to MyDelegate.Invoke() - a call to the generated Invoke method. The IL for the call is simply *callvirt instance void ConsoleApplication1.Program/dostuff::Invoke(string)* which is no different from any other method call. – Mongus Pong Jun 17 '11 at 16:22

1 Answers1

9

The voodoo can be found at the end of the signature: runtime managed. Notice that all of your managed classes and methods that you define will be decorated as cli managed.

runtime managed means that the runtime provides pre-optimized implementations of the methods.

Ethan Cabiac
  • 4,943
  • 20
  • 36
  • The delegate does have behaviour. It loops over its invocation list - a delegate can represent multiple methods to call - and calls each method in turn. – Mongus Pong Jun 17 '11 at 16:31
  • I can't see how the implementing method can override the behaviour. It is an interesting pattern, but I can't see any evidence of this being the way it works. It wouldn't work for multicast delegates though. When creating the delegate it is definitely the generated delegate class that gets created and its constructor is called with the method passed to it. There is no voodoo here, it is just creating the generated delegate class just like any normal class is created. – Mongus Pong Jun 17 '11 at 16:35
  • @Mongus, updated my answer. Note however that the "behavior" for iterating over the invocation list is not part of delegate, but part of System.Delegate. – Ethan Cabiac Jun 17 '11 at 17:37
  • @Mongus: all delegates have been multicast since at least .NET 2.0. – Anton Tykhyy Jun 17 '11 at 17:41
  • ah! So it is voodoo after all! Thanks ;) – Mongus Pong Jun 17 '11 at 19:28