Of all the new features in C# 3.0, Lambda expressions have to be one of my favourites.

One non-obvious way that they can be used is as event handlers, in just the way that anonymous delegates could be.

Consider these examples, handling the AfterExpand method of a WinForms TreeView.

Original code, from the era of C# 2.0:

    treeView.AfterExpand +=
        new TreeViewEventHandler(
            delegate(object o, TreeViewEventArgs t)
            {
                t.Node.ImageIndex = (int)FolderIconEnum.open;
                t.Node.SelectedImageIndex = (int)FolderIconEnum.open;
            }
        ); 

First, lets swap out the delegate for a lambda expression:

    treeView.AfterExpand +=
        new TreeViewEventHandler(
            (object o, TreeViewEventArgs t) =>
            {
                t.Node.ImageIndex = (int) FolderIconEnum.open;
                t.Node.SelectedImageIndex = (int) FolderIconEnum.open;
            }
        );

The C# compiler is willing to infer the new TreeViewEventHandler(), so we can leave it out:

    treeView.AfterExpand +=
        (object o, TreeViewEventArgs t) =>
        {
            t.Node.ImageIndex = (int) FolderIconEnum.open;
            t.Node.SelectedImageIndex = (int) FolderIconEnum.open;
        };

Now, the types of the arguments to the lamda expression can be inferred:

    treeView.AfterExpand +=
        (o, t) =>
        {
            t.Node.ImageIndex = (int) FolderIconEnum.open;
            t.Node.SelectedImageIndex = (int) FolderIconEnum.open;
        };

Simple, clean and easy to read … well, once you’re used to it, anyway.

Comments

blog comments powered by Disqus
Next Post
Be A Better Developer  10 Feb 2009
Prior Post
Upgrades that (mostly) Work  07 Feb 2009
Related Posts
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
Pass implementations, not representations  14 Oct 2017
Avoiding the Singleton Pattern  22 Jul 2017
Implementing the Singleton Pattern  15 Jul 2017
More smart-code posts »
Related Pages
February 2009 archive