I have a ugly piece of code that adds event handlers. The problem is, if the code is called multiple times, the event handlers are called multiple times.
To solve the problem, I remove the event handler first and then add it.
Now I’ve seen the following behaviour:
Some event handlers can be checked like:
if (object.event == null) {
//
// Code
//
}
others of the form
if (object.object.event == null) {
//
// Code
//
}
I get a message like ‘object.object.event’ may only occur left of -= or +=.
(Since I’m using a german version of visual studio, I don’t know the correct translation to english).
I have no idea why the behaviour looks this inconsequent so I would be grateful for some information on this.
To be more specific: It’s user control.
if (myControl.Event == null) {
//
// works
//
}
if (myControl.TreeView.NodeMouseClick == null) {
//
// doesn't work
//
}
SLaks is correct, and has linked to some excellent resources. Here’s a relevant quote from Chris Burrows’ blog article:
In your case, when resolving
myControl.Event, you’re inside themyControlclass, so you don’t see an event object; instead you see an actual delegate object, which you can compare with null. When resolvingmyControl.TreeView.NodeMouseClick, you’re outside theTreeViewclass, so you can’t access the actual delegate object; all you get is the event object, which cannot be compared to null.If I understand correctly, all of this wouldn’t help you anyway, since presumably after you check for null, you’re going to try to fire the
TreeView‘s event for it, which you can’t do.Depending on what you’re trying to do, you could probably subclass
TreeViewand add aninternalmethod that would call the protectedTreeView.OnNodeMouseClickmethod to fire the event.