Is it a bad practice to write inline event handlers

Is it bad practice to write inline event handlers?

For me, I prefer to use it when I want to use a local variable in an event handler, as shown below:

I prefer this:

// This is just a sample private void Foo() { Timer timer = new Timer() { Interval = 1000 }; int counter = 0; // counter has just this mission timer.Tick += (s, e) => myTextBox.Text = (counter++).ToString(); timer.Start(); } 

Instead of this:

 int counter = 0; // No need for this out of Boo & the event handler private void Boo() { Timer timer = new Timer() { Interval = 1000 }; timer.Tick += timer_Tick; timer.Start(); } void timer_Tick(object sender, EventArgs e) { myTextBox.Text = (counter++).ToString(); } 
+49
c # event-handling inline-code
Oct. 31 '10 at 15:41
source share
3 answers

This is completely normal - although there are two caveats:

  • If you change a local variable from a closure, you must make sure that you understand what you are doing.
  • You will not be able to unsubscribe from the event.

Usually I am only built-in to really simple event handlers - for something more, I use lambda expressions (or anonymous methods) to sign up with a method call with a more suitable method:

 // We don't care about the arguments here; SaveDocument shouldn't need parameters saveButton.Click += delegate { SaveDocument(); }; 
+63
Oct 31 '10 at 15:51
source share

In most cases, I would prefer to have separate methods like "timer_Tick ()", however I would prefer it to be called OnTimerTick () as:

  • When I read the class, purer wheat occurs. "On" tells me its event handler.
  • It is easier to set a breakpoint in a method in the "inline" case.
  • The event is fired long after the contractor "Foo" has returned, and I do not think that it works as part of the contractor.

However, if the event is fired only before the method is declared as a string, and the object on which the event is set has a scope limited by the declaration method, then I think that the on-line version is better. So I like to use "in line" to pass the sort method to the delegate.

+3
Nov 01 '10 at
source share

You put two samples together. It is clear that the second option (which you do not prefer) is the most readable one.

Readability and maintainability of the code are very important. Keep things simple, as clear as possible. Lambda expressions are generally considered more difficult for most people to understand. Even if this is the second nature for you, for others it may not be so.

0
Oct. 31 '10 at 21:12
source share



All Articles