Delegates, Events and The 10 Type Members of C#

Have you ever stopped to think about the different ‘kinds‘ of things you can put in a class?

If your colleagues are that way inclined, then I’d encourage you to ask. I’ll bet no-one gets all of them.

Here they are:

1. Methods
2. Fields
3. Properties
4. Type Declarations (e.g. Nested Class)
5. Type (static) Constructors
6. Instance Constructors
7. Events
8. Operator Overloads
9. Conversion Operators
10. Constants

When I asked a colleague here, he included delegates in that list. I was stumped! Surely delegate should appear. Should my list should Go Up To 11?

I got back to my desk and thought about it, and then the penny dropped.

First, we have to decide if we’re talking about delegate types or delegate instances. The failure to differentiate these is the source of most the confusion that I have encountered that surround delegates. Armed with this info we can start referencing our list above:

A delegate type is a type declaration. Like a class, struct or enum. So, that means it is classified by number 4 in our list above.

If we’re talking about a delegate instance then a this is just an instance of a type. If we put one of them in a class, it’s a field (2) or maybe a property (3).

The difference between these two is the same as the difference between a nested class and an instance of a class.

So, why is an event so special about an event? Well, it’s a special sort of ‘thing’. It differs subtly from a TypeField or Property enough to distinguish it from them. It all boils down to an understanding of the difference between delegates and events. Jon Skeet has a nice article about this:

Events are pairs of methods, appropriately decorated in IL to tie them together and let languages know that the methods represent events.

We already distinguish a Property as being something different from a Field. When compiled, a Property becomes a pair of methods with backing field. In a similar fashion, an Event becomes a pair of methods with a backing class that utilises these methods.

So there we are. Events are a special sort of Thing you put in another Thing and are enough to be a Thing In Its Own right and not just a sort of other Thing.



Leave a Reply