tags:

views:

129

answers:

3

I am looking at this event example http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx

This all makes sense to me except that the following line

public event ChangedEventHandler Changed;

What does this do?? Is this some sort of list of EVentCallbacks?? Why is new not used here??

EDIT: Why does this not need a NEW keyword??

public event ChangedEventHandler Changed;

A: 

This is your actual custom event to which you attach your event handlers.

RaYell
A: 

What it's doing is associating an event named Changed with the ChangedEventHandler delegate.

R. Bemrose
+2  A: 

It's declaring a field-like event, of type ChangedEventhandler, called Changed. Basically it's roughly equivalent to:

private ChangedEventHandler changedHandler;

public event ChangedEventHandler Changed
{
   add
   {
       lock(this)
       {
           changedHandler += value;
       }
   }
   remove
   {
       lock(this)
       {
           changedHandler -= value;
       }
   }
}

In other words, it creates an event which clients can subscribe to and unsubscribe from, and a variable to store those subscriptions. The event subscription/unsubscription code just combines/removes the given handler with the existing ones and stores the result in the field.

The result is that clients can subscribe to the event, e.g.

foo.Changed += ...;

and then when you raise the event, all the handlers are called.

See my article on events and delegates for more information.

Jon Skeet
Thanks - I am actually reading your MiscUtils code :-)...Why dont you use private ChangedEventHandler changedHandler = new ChangeEventHandler...??
ChloeRadshaw
What do you mean, exactly?
Jon Skeet
What I mean is why do events not have to be decalred with the new keyword?? This seems really strange to me.Put differently you say "variable to store those subscriptions" - How is this field allocated? When does this field get allocated? Thats what makes no sense
ChloeRadshaw
@ChloeRadshaw: Why would they have to be declared with "new"? You don't write "new" for properties, or methods, or variables, do you? The variable in the above is the "private ChangedEventHandler changedHandler" - its default value is null, just like any other reference type field.
Jon Skeet