Tom Fischer

  Home  |   Contact  |   Syndication    |   Login
  21 Posts | 0 Stories | 44 Comments | 0 Trackbacks

News

Archives

Post Categories

.NET Framwork

TFS

Tools

Visual Studio

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

posted on Friday, September 12, 2008 4:35 PM

Feedback

# re: C# Events and Delegates in 3 seconds 9/15/2008 6:28 PM Amre Ellafi
short but cool , worth bookmarking :)

# re: C# Events and Delegates in 3 seconds 9/1/2009 10:26 AM HTK
I agree with the earlier poster, this mini article is cool because its very clear, to the point and short.

Worth bookmarking indeed!

Thanks!

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: