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