3

This is a very simple question. I'm asking because I've never seen it before which makes me wonder if there's something wrong.

comboBox1.MouseEnter += (a, b) => comboBox1.Focus();
campaignDataGridView.MouseEnter += (a, b) => campaignDataGridView.Focus();
Aaron Anodide
  • 16,906
  • 15
  • 62
  • 121

2 Answers2

10

This is perfectly acceptable, however, since these are anonymous delegates, there is no way to unsubscribe the event handler.

That is:

// Subscribe lambda as event handler
comboBox1.MouseEnter += (a, b) => comboBox1.Focus(); 

// Try to unsubscribe a _different_ lambda with identical syntax. 
// The first lambda is still subscribed
comboBox1.MouseEnter -= (a, b) => comboBox1.Focus(); 

Whether that is a problem or not depends on your application and use.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
6

It is fine; the only subtle point is if you need to unsubscribe it; then you need to store the delegate locally too:

EventHandler handler = (s,a) => ...
obj.SomeEvent += handler;
...
obj.SomeEvent -= handler;

Note that if I'm not using either parameter (sender/args) I prefer the anon method syntax:

obj.SomeEvent += delegate {...};

As this doesn't introduce any extra (unnecessary) variables into scope.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900