James Berry <[EMAIL PROTECTED]> wrote:

> A colleague has been writing code and has missed the "event" keyword from his 
> event definitions
> 
> Eg:
> 
>   public class Foo {
>         public EventHandler FooChanged;
>   }
> 
> He appears to be able to subscribe to these "events" in the normal fashion:
> 
>   x.FooChanged += new EventHandler(blah)
> 
> 
> He asked me what difference the event keyword made and I said I thought it 
> was 
> to do with attaching multiple subscribers, but I must admit I was surprised 
> that the "+=" syntax above worked.  I would have expected that since 
> EventHandler 
> is a delegate he would have had to have used just a normal assignment instead 
> to make it work.

A delegate (e.g. EventHandler) is a type: it's a linked list of method
pointers of a particular signature.

The fact that it's a linked list means you can combine two delegates
into a single list with '+=': it's exactly equivalent to:

    x.FooChanged = x.FooChanged + new EventHandler(blah);

(The 'new EventHandler()' bit isn't needed since C# 2.0; can be replaced
with just 'blah'.)

The above, in turn, is equivalent to:

    x.FooChanged = (EventHandler) Delegate.Combine(x.FooChanged,
        new EventHandler(blah));

An event, from the outside (i.e. users of the class), is like a
write-only property; but rather than having a 'set' accessor, it has
'add' and 'remove' accessors. Indeed, it can be written just like a
property:

    public event EventHandler FooChanged
    {
        add { /* ... value is added ... */ }
        remove { /* ... value is removed ... */ }
    }

If you don't write these handlers yourself, the C# compiler provides an
automatic implementation of add and remove that simply perform '+=' and
'-=' on a hidden private field of type EventHandler (in this case).

From within the body of the class, an event using the non-explicit
syntax can be invoked; what this does is invoke the delegate in the
hidden private field.

If the event is using explicit syntax, the compiler can't do that,
because it doesn't know where you've stuffed the events; in that case,
you need to do the invoking yourself. One place to stuff them is in a
hash table. This saves wasting a bunch of space for event handler fields
that aren't commonly implemented.

-- Barry

-- 
http://barrkel.blogspot.com/

===================================
This list is hosted by DevelopMentor®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to