Detecting EventHandler

  • Thread starter Thread starter Eddy POULLET
  • Start date Start date
E

Eddy POULLET

hi,

I have a control with an event handler

this.Button.Click += new System.EventHandler(this.FormData_Changed);

Apparently the code below is not compilable

if ( this.Button.Click != null) // CS0079
{
....
}

Question : How can I known if a (or how much) handler exists for an
event ?

To avoid recursion, I do

this.Button.Click -= new System.EventHandler(this.FormData_Changed);
....
this.Button.Click += new System.EventHandler(this.FormData_Changed);

But I would write to have a cleaner code :


bExist = false;
if (this.Button.Click != null)
{
this.Button.Click -= new System.EventHandler(this.FormData_Changed);
bExist = true;
}
....
....
if (bExist)
this.Button.Click += new System.EventHandler(this.FormData_Changed);

Thanks a lot,

Eddy POULLET
Brussels
 
Thanks for the reply

I have tested so:

Delegate[] DelegateList = ((MulticastDelegate
(this.Button.Click)).GetInvocationList();

But when compiling, I have allways the same error :

The event... can only appear on the left hand sideof += or -=.
Any other idea?

Eddy POULLET
Brussels
 
Hi Eddy,

You cannot check an event for handlers. The event is simply pair (or three)
methods - 'add', 'remove' (and it could have 'fire' method ). Unlike the
property's accessors add a and remove doesn't return value so you cannot
check events against anything. So that is what is visible from outside the
object that exposes an event. When you program the class methods though
depending on how the event are implemented you can check for handlers. If
you have back-up delegate field (the default case when you declare an
even)you can simply check that field for null. You may also keep the
delegates in a collection (as window forms controls do) in this case you
should use appropriate technique.
 
Hi Eddy,

I can recall I've seen something about it either in Jeffery Richter's
'Applied Microsoft .NET Framework Programming ' or Don Box's 'Essential
..NET, Volume I: The Common Language Runtime'. Frankly I don't remember.
Anyways both are excellent books. I believe there are articles about this on
the net, but I don't know of any
 
Hi,

I have the book of Jeff Richter's; I will loo at it.

Anyway, thank you for the help.

Eddy POULLET
Brussels
 
Back
Top