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
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
Archives
February 2009
2009