C# Events and Delegates in 3 seconds

C# Events and Delegates in 3 seconds

C#, Events and Delegates as an Elevator Pitch - Or in 3 seconds

Here are the elevator pitches you should know about events and delegates:

   A Delegate is a (or collection of) strongly typed FunctionPointer(s)

   An Event is a wrapped Delegate 
 

But to be honest this is not big news and not the reason for this blog. I thought this would make a nice starter... Like when you go for a nice dinner.  Today I had the chance to look under the hood and I was astonished to see what really happens. This made me think... hmm sounds like an interesting post for Friday afternoon. (Thank you Mark!)

So let's take a second to verify the second statement. An Event is a wrapped Delegate:

First we define an Event and subscribe to it:

//Test class with the event public class TomsEventClass { public event EventHandler ItsTomTime; }

//test program class Program { static void Main(string[] args) { TomsEventClass tom = new TomsEventClass(); tom.ItsTomTime += tom_ItsTomTime; } static void tom_ItsTomTime(object sender, EventArgs e) { //let's see what we can do it } }

But what was actually generated by the compiler? Let's use Reflector to look at the IL

The Event gets translated into one private delegate:

.field private class [mscorlib]System.EventHandler ItsTomTime

... and into two public methods to add and remove Subscribers:

.event [mscorlib]System.EventHandler ItsTomTime { .addon instance void ConsoleApplication3.TomsEventClass::add_ItsTomTime(class [mscorlib]System.EventHandler) .removeon instance void ConsoleApplication3.TomsEventClass::remove_ItsTomTime(class [mscorlib]System.EventHandler) }

And when we subscribe we see we actually call the generated add_ItsTomTime method:

callvirt instance void ConsoleApplication3.TomsEventClass::add_ItsTomTime(class [mscorlib]System.EventHandler)

That's it!

I have to admit, even knowing that events where restriced delegates I never took the time to really look under the hood.
This won't make me a better programer but it is fun to know (at least for a Geek on geekswithblogs :-)

Tom

This article is part of the GWB Archives. Original Author: ftom

New on Geeks with Blogs