"Guadala Harry" <gh****@aol.com> wrote in message
news:uz**************@TK2MSFTNGP10.phx.gbl...
In the following line of code, what is the point of including the 'new'
keyword?
List.Changed -= new ChangedEventHandler(ListChanged);
I'm just a bit confused because I thought 'new' was used to instantiate a
new instance of a class - and in this case, were removing an 'existing'
instance of the ChangedEventHandler delegate from the List.Changed event.
Thanks.
The += operator (and the + operator for the more general case) will add a
delegate to the event. In part, the delegate in this case, defines a method
and either a class (for a static method) or an instance.
The -= operator will remove a delegate - but you must specify which delegate
to remove - this is done by identifying the method and the class or instance
object. The only mechanism that we have to do this is through the new
XXXX(yyyy) where XXXX is a type speficier for the delegate, and yyyy
identifies the method and class/instance object.
Consider the following:
List.Changed = new ChangedEventHandler(MyMethod1);
List.Changed += new ChangedEventHandler(MyMethod2);
....
List.Changed -= new ChangedEventHandler(MyMethod1);
This sequence will create an event with one delegate, then create another
event with the first plus one more (events are immutable - things are not
added to nor subtracted from then). Finally, a third event will be created,
but the MyMethod1 delegate will not be there. The second delegate for
MyMethod2 was created ONLY to get the method and class/instance object,
nothing more.
Had one found the prescience to keep a reference to the first delegate, one
might then be able to do something like this:
List.Changed = myDelegate = new ChangedEventHandler(MyMethod1);
List.Changed += new ChangedEventHandler(MyMethod2);
....
List.Changed -= myDelegate;
While that may be a bit more efficient, it's functionally equivalent with
the code above.
regards
roy fine