In this post I’ll explore the MSIL generated for delegates and events when a project is compiled in Visual C# or any other language that target the .NET platform. This is my fourth post on exploring MSIL – Microsoft Intermediate Language.
Here are the links for my last three posts.
The lies of the C# compiler : It explores the MSIL equivalent of the C# accessors like protected, internal etc.
Exploring MSIL – Static and Instance Methods : It explores the difference in the MSIL generated for static and instance methods.
Exploring MSIL – Properties : It explores the generated MSIL for properties of a class.
As in the last posts, I’ll create a project with a class – Traffic light that contains the event SignalChanged. This event uses the delegate SignalChangedDelegate that encapsulates the methods that can be called once the event is triggered. Here goes the code.
public delegate void SignalChangedDelegate(string newSignal);
class TrafficLight
{
public event SignalChangedDelegate SignalChanged;
}
Now let us start by looking at the MSIL generated generated for the delegate – SignalChangedDelegate.
The delegate, SignalChangedDelegate, is actually a class that extends the class MulticastDelegate. The constructor, .ctor, takes 2 arguments – an object and a native int. Apart from the constructor there are three other methods -
1. BeginInvoke() method takes a string , a AsyncCallback and an object as arguments and returns an IAsyncResult.
2. EndInvoke() method takes an IAsyncResult and returns a void.
3. Invoke() method takes a string and returns void.
And here is the MSIL for the class TrafficLight that defines the event SignalChanged.
The points to note are
1. A private field of the type of the SignalChangedDelegate is generated. The name of the field is same as that of the event which is shown by an inverted green triangle at the bottom of the image.
2. Two additional methods – add_SignalChanged and remove_SignalChanged are also generated and both of them take the SignalChangedDelegate as argument. Actually these are the methods that are called once listeners add or remove themselves for the SignalChanged event.
3. The event SignalChanged is also present which is as it is in the source code.
In the next post I am directly diving into the MSIL instructions and I’ll start with the example that every one starts with – The Hello World Program.


[...] Check it out! While looking through the blogosphere we stumbled on an interesting post today.Here’s a quick excerptIn this post I ll explore the MSIL generated for delegates and events when a project is compiled in Visual C# or any other language that target the .NET platform. This is my fourth post on exploring MSIL – Microsoft Intermediate Language. Here are the links for my last three posts. The lies of the C# compiler : It explores the MSIL equivalent of the C# accessors like protected, internal etc. Exploring MSIL – Static and Instance Methods : It explores the difference in the MSIL [...]