FlexLib Adding Event Handlers

  • 1
  • Question
  • Updated 1 month ago
The general model for adding an event handler in a FlexLib program appears to be:

_radio.PropertyChanged += new PropertyChangedEventHandler(<your event handling function>)

However, it seems that in my simplistic testing

_radio.PropertyChanged += <your event handling function>

seems to work. I'm new to C#, I don't understand the difference.

Also, I assume that the += operator adds an event handler, so that any previous event handler is called, but looking at the event dispatching code in Radio.cs, I don't see any iteration through a list of event handlers.

Thanks, 73,
Photo of Mark Erbaugh

Mark Erbaugh

  • 510 Posts
  • 43 Reply Likes

Posted 2 months ago

  • 1
Photo of Mark - WS7M

Mark - WS7M

  • 1335 Posts
  • 501 Reply Likes
Hi Mark,

PropertyChangedEventHandler is a wrapper that just invokes your method.  So your second way is fully functional and achieves pretty much the same thing.

I believe that PropertyChangedEventHandler has some protection in it but I honestly do not use it so I cannot say for sure.

I do it as you do your second implementation.

One important thing:

It is important when you add event handlers to later remove them.  This is most important when something is created and later removed.  If you are setting the event handler and it stays in place the entire life of your program then it is not a big deal. 

But the general practice is to:

the_event += myhandler

then in dispose or some other deconstructing place do:

the_event -= myhandler.

If you don't do this and your program continues to run very strange things can happen.

Photo of Mark Erbaugh

Mark Erbaugh

  • 510 Posts
  • 43 Reply Likes

I posted this same question elsewhere, but since you mentioned it:  If I create an event handler by using new (i.e. the_event += new EventHandlerType(EventHandlerMethod);

I don't have a reference to the event handler for use in removing it. How would you remove the event handler in this case?

If I do the_event -= new EvenHandlerType(EventHandlerMethod); will that actually remove the event handler?

Mark - N8ME
Photo of James Smith

James Smith

  • 6 Posts
  • 0 Reply Likes