Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices of using lambda expressions for event handlers

Tags:

c#

lambda

events

After discovering lambda expressions, and their use as anonymous functions, I've found myself writing a lot of more trivial events such as these:

txtLogin.GotFocus += (o, e) =>
{
    txtLogin.Text = string.Empty;
    txtLogin.ForeColor = SystemColors.ControlText;
};
txtLogin.LostFocus += (o, e) =>
{
    txtLogin.Text = "Login...";
    txtLogin.ForeColor = SystemColors.InactiveCaptionText;
};

I've also moved away from event handlers which just call other functions, replacing them with small lambdas which do the same:

backgroundWorker.DoWork += (o, e) => DatabaseLookup.Open(e.Argument as string);

I've found some similar questions addressing performance concerns and pointing out that you can't remove them, but I haven't found any addressing the simple question of is this a good idea?

Is the use of lambdas in such a way considered good form, or do more experience programmers look down on this? Does it hide event handlers in hard-to-find places, or does it do the code a service by reducing the number of trivial event handlers?

like image 659
dlras2 Avatar asked Jul 14 '10 16:07

dlras2


1 Answers

It's a perfectly reasonable idea - but in this particular case, I would use an anonymous method instead:

txtLogin.LostFocus += delegate
{
    txtLogin.Text = "Login...";
    txtLogin.ForeColor = SystemColors.InactiveCaptionText;
};

The benefit is that you don't have to specify the parameters - which makes it clearer that you're not using them. This is the only advantage that anonymous methods have over lambda expressions.

The performance hit is almost always going to be negligible. The inability to remove them afterwards is a very real problem if you do need to be able to remove the handler, but I find that often I don't. (Reactive Extensions has a nice approach to this - when you subscribe to an observable sequence, you're given back an IDisposable which will remove the subscription if you call it. Very neat.)

like image 89
Jon Skeet Avatar answered Oct 12 '22 22:10

Jon Skeet