Events Are Not Delegates – but look like they are

Following on from the Delegates post…

I have always thought that Events in C# are delegates; or at least are involved with them – but I’m wrong! ( not for the first time nor the last)

Again- taken from TAKEN FROM C# In Depth Third Edition  Just read this explanation

Developers often confuse events and delegate instances, or events and fields declared with delegate types. The difference is important – events aren’t fields. C# provides a shorthand in the form of field like events.

Its helpful to think of events being similar to properties  – When you use properties it looks like your fetching or assigning values directly to fields, but you’re actually calling methods (getters and setters)…

Likewise, when you subscribe to or unsubscribe from an event it looks like your using a filed whose type is a delegate type, with the += and -= operators….

The reason for having events in the first place is much like the reason for having properties – they add a layer of encapsulation, implementing the publish /subscribe pattern.

Field-like events make the implementation of all of this much simpler to look at – a single declaration and you’re done. The compiler turns the declaration into both an even with default add / remove implementations and a private field of the same type – Just like a property

This make sit look as if you can invoke an event, but what you actually do to call the event handlers is invoke the delegate instance stored in the field.

So – who knew that! – Well Jon Skeet did, as he wrote the book TAKEN FROM C# In Depth Third Edition 

Nothing like unlearning something which you thought you knew!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s