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
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
Static Analysis tools for the Win  15 Apr 2017
Exception Logging  19 Jan 2016
On the Merits of Simple Code  28 Nov 2015
Semantic Types  27 Sep 2015
Command Line Processing  21 Sep 2014
Easy String Conversion  24 Aug 2014
More smart-code posts »
Related Pages
February 2009 archive