Wiring Up Events with Lambda Expressions in C#

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.

Example 1. Adding event handler using lambda expression:

public Form1()

{

InitializeComponent();

// Use a lambda expression to define an event handler.

this.Click += (s,e) => { MessageBox.Show(((MouseEventArgs)e).Location.ToString());};

}

Example 2.

this.Load += (s, ev) =>

HtmlMeta hma = new HtmlMeta();

hma.Name = “viewport”;

hma.Content = “width=device-width”;

this.Header.Controls.Add(hma);

};

Example 3. Handling the AfterExpand method of a WinForms TreeView in C# 2.0:

treeView.AfterExpand += new TreeViewEventHandler(

delegate(object o, TreeViewEventArgs t)

{

t.Node.ImageIndex = (int)FolderIconEnum.open;

t.Node.SelectedImageIndex = (int)FolderIconEnum.open;

}

);

Using Lambdas to make the code clean and easy to read:

treeView.AfterExpand += (o, t) =>

{

t.Node.ImageIndex = (int) FolderIconEnum.open;

t.Node.SelectedImageIndex = (int) FolderIconEnum.open;

};

Copyright © All Rights Reserved - C# Learners