tags:

views:

86

answers:

3

Hi All,

I have a basic doubt. Internally how are events represented as methods or as (fields)objects. If event is a field then how one can still contain events in the interface definition.

Thanks JeeZ

A: 

Events are not represented as fields nor methods. They are simply events, as far as the meta-data for a class is concerned.

Similarly properties have a special flag (although these get stored as methods with well known names).

Rowland Shaw
+6  A: 

If you type this:

public event EventHandler MyEvent;

what the compiler generates is (simplified) this:

// declares a normal delegate of type 'EventHandler'
private EventHandler _myEvent;

// declares 'add_MyEvent' and 'remove_MyEvent' methods similar to a property
public event EventHandler MyEvent {
    add { _myEvent += value; }
    remove { _myEvent -= value; }
}

An event is similar to a property; a wrapper around a delegate that only allows methods to be added or removed. This is so you can't completely re-assign the delegate and delete other people's subscriptions to it.

All you are doing when specifying an event in an interface is that any implementing classes should have the add and remove methods for the event. Very similar to declaring a property on an interface, in fact.

This is also why you can only call or re-assign the event in the class it is declared in - any references to the MyEvent event within the class are re-routed to use the delegate directly, whereas outside the class you can only access the add and remove methods, not the delegate directly.

thecoop
And the "simplified" is about as close as you can get without having to discuss at least 3 different compiler implementations ;-p
Marc Gravell
+2  A: 

@thecoop's answer is a very good description of "field-like events" (noting the "simplified" caveat) - but note that actually events can be implemented any way you like. All the event defines is an add/remove accessor pair (which is why it can be defined on the interface, like a property).

For example, with sparce events the following may be common:

private static readonly object FooKey = new object(), BarKey = new object();

public event EventHandler Foo {
    add {Events.AddHandler(FooKey, value);}
    remove {Events.RemoveHandler(FooKey, value);}
}
public event MouseClickEventHandler Bar {
    add {Events.AddHandler(BarKey, value);}
    remove {Events.RemoveHandler(BarKey, value);}
}

where Events is an EventHandlerList, usually delay-loaded:

private EventHandlerList events;
protected EventHandlerList Events {
    get {
        if(events == null) events = new EventHandlerList();
        return events;
    }
}

Or you could do anything else you like. Within reason (noting the expected behaviour of event subscriptions and delegate equality / composite delegates).

Marc Gravell
Another neat thing I do with event methods is implement a direct route-through to an event on a child control (for winforms) :)
thecoop