Home  • Programming • C#.NET

Using Lambda Expressions as Event Handler

a-lambda-expression-is-anA lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions. To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. Lambda expressions can be used to tie event handling code to an event. Lambda expressions assume implicit data typing which means you do not have to figure out the data type of the event’s e parameter—the compiler will do it for you. 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;
        };

Share

Copyright © 2024. Powered by Intellect Software Ltd