views:

726

answers:

3

I've seen some very good questions on Stack Overflow concerning delegates, events, and the .NET implementation of these two features. One question in particular, "How do C# Events work behind the scenes?", produced a great answer that explains some subtle points very well.

The answer to the above question makes this point:

When you declare a field-like event ... the compiler generates the methods and a private field (of the same type as the delegate). Within the class, when you refer to ElementAddedEvent you're referring to the field. Outside the class, you're referring to the field

An MSDN article linked from the same question ("Field-like events") adds:

The notion of raising an event is precisely equivalent to invoking the delegate represented by the event — thus, there are no special language constructs for raising events.

Wanting to examine further, I built a test project in order to view the IL that an event and a delegate are compiled to:

public class TestClass
{
    public EventHandler handler;
    public event EventHandler FooEvent;

    public TestClass()
    { }
}

I expected the delegate field handler and the event FooEvent to compile to roughly the same IL code, with some additional methods to wrap access to the compiler-generated FooEvent field. But the IL generated wasn't quite what I expected:

.class public auto ansi beforefieldinit TestClass
    extends [mscorlib]System.Object
{
    .event [mscorlib]System.EventHandler FooEvent
    {
        .addon instance void TestClass::add_FooEvent(class [mscorlib]System.EventHandler)
        .removeon instance void TestClass::remove_FooEvent(class [mscorlib]System.EventHandler)
    }

    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
        // Constructor IL hidden
    }

    .field private class [mscorlib]System.EventHandler FooEvent
    .field public class [mscorlib]System.EventHandler handler
}

Since events are nothing more than delegates with compiler-generated add and remove methods, I didn't expect to see events treated as anything more than that in IL. But the add and remove methods are defined in a section that begins .event, not .method as normal methods are.

My ultimate questions are: if events are implemented simply as delegates with accessor methods, what is the point of having a .event IL section? Couldn't they be implemented in IL without this by using .method sections? Is .event equivalent to .method?

+4  A: 

I'm not sure that is surprising... compare to the same for properties vs fields (since properties before the same function as events: encapsulation via accessors):

.field public string Foo // public field
.property instance string Bar // public property
{
    .get instance string MyType::get_Bar()
    .set instance void MyType::set_Bar(string)
}

Also - events do not mention anything about fields; they only define the accessors (add/remove). The delegate backer is an implementation detail; it just so happens that field-like-events declare a field as a backing member - in the same way that auto-implemented-properties declare a field as a backing member. Other implementations are possible (and very common, especially in forms etc).

Other common implementations:

Sparse-events (Controls, etc) - EventHandlerList (or similar):

// only one instance field no matter how many events;
// very useful if we expect most events to be unsubscribed
private EventHandlerList events = new EventHandlerList();
protected EventHandlerList Events {
    get { return events; } // usually lazy
}

// this code repeated per event
private static readonly object FooEvent = new object();
public event EventHandler Foo
{
    add { Events.AddHandler(FooEvent, value); }
    remove { Events.RemoveHandler(FooEvent, value); }
}
protected virtual void OnFoo()
{
    EventHandler handler = Events[FooEvent] as EventHandler;
    if (handler != null) handler(this, EventArgs.Empty);
}

(the above is pretty-much the backbone of win-forms events)

Facade (although this confuses the "sender" a little; some intermediary code is often helpful):

private Bar wrappedObject; // via ctor
public event EventHandler SomeEvent
{
    add { wrappedObject.SomeOtherEvent += value; }
    remove { wrappedObject.SomeOtherEvent -= value; }
}

(the above can also be used to effectively rename an event)

Marc Gravell
Can you give some more detail about other implementations that are common? I assume you're talking about other implementations than using a field as a backing memeber, not other implementations than using a delegate of any type as a backing memeber.
Chris Stevens
Thanks for the update. How can I specify that I want an event implemented using an EventHandlerList instead of a delegate field as a backing member? If the default behavior of the `event` keyword is to use a delegate field, do I have to bypass C# entirely and write the IL directly?
Chris Stevens
I wrote it above, already. The default *if you don't specify add/remove* is to use a delegate field. If you specify add/remove (like above) you can do what you like. It would probably be possible to also do this via postsharp, but I'm not sure I'd bother...
Marc Gravell
Note that you could probably use a "snippet" in the IDE to simplify things...
Marc Gravell
+1  A: 

Events aren't the same as delegates. Events encapsulate adding/removing a handler for an event. The handler is represented with a delegate.

You could just write AddClickHandler/RemoveClickHandler etc for every event - but it would be relatively painful, and wouldn't make it easy for tools like VS to separate out events from anything else.

This is just like properties really - you could write GetSize/SetSize etc (as you do in Java) but by separating out properties, there are syntactical shortcuts available and better tool support.

Jon Skeet
You can do the same thing with delegates, they support += combining (even with null delegates)
Pop Catalin
But they don't *just* support += - that's the point.
Jon Skeet
The downside of course is that you can't refactor or build higher level code with events. Like the "Async Event-based" stuff MS is so hot on now -- pain to code to it generically, since you can't reference the event delegate and get its type passed along...
MichaelGG
A: 

The point of having events that are a pair of add, remove, methods is encapsulation.

Most of the time events are used as is, but other times you don't want to store the delegates attached to the event in a field, or you want to do extra processing on add or remove event methods.

For example one way to implement memory efficient events is to store the delegates in a dictionary rather than a private field, because fields are always allocated while a dictionary only grows in size when items are added. This model is similar with what Winforms and WPF uses make make efficient use of memory (winforms and WPF uses keyed dictionaries to store delegates not lists)

Pop Catalin