The face of Garbo is an Idea, that of Hepburn an Event.
Roland Barthes

Man must be prepared for every event of life, for there is nothing that is durable.
Menander

The first fall of snow is not only an event, it is a magical event. You go to bed in one kind of world and wake up in another quite different, and if this is not enchantment then where is it to be found?
J. B. (John Boynton) Priestley

Literature is analysis after the event.
Doris Lessing

The other day, my application needed an event handler.   An appropriate delegate was created and it worked great.   But I wanted to determine what the best practices are for event handlers.   For instance, a click event for a button is defined in the designer as

If the += is replaced with an =, a compiler error is generated.   An event can only appear on the left hand side of += or -=.   The events I create need to have this same compiler protection.   The generic class EventHandler<T> is an exact fit with my needs.

First, create a custom event arguments class  by inheriting from the class EventArgs.

Next, create an event that uses the custom event arguments shown above.  public event EventHandler<DataChangeEventArgs> DataChange = null; Wire this event into a class property.  In this case, fire the event(s) whenever the DataChanged property changes from false to true or true to false.  Notice in the set method, the event does not fire if the new value is the same as the current value.

To show the event in action, let’s create a simple class with three properties.  LastName, FirstName,  Age and the DataChange event as shown above.  The code stub for FirstName is shown below.  LastName and Age are nearly identical.  DataChanged is only set to true if the property value changed and the DataChange event only fires when the DataChanged property toggles between true/false or false/true.

Each Event Handler, A, B and C looks the same.  The code below shows the A event handler.

The test code below will run through multiple scenarios to verify that the event handlers are firing when I expect them to fire.  The highlighted line of code will be described after this block of code.

The test results are shown below.

I highlighted the section of code because I began to wonder.  After adding the B Event Handler three times, I wondered if I could remove all the B Event Handlers with a single line of code instead of removing it three times.  I wrote the code that follows that can remove all instances of a single event handler or remove all event handlers.   This code may not be the wisest for real applications.  Event Handlers could be on different threads but this code will still remove them.

Download Solution Files

Tags:

Leave a Reply


*