Using Lambda Expressions in C#

What is a Lambda Expression?

A lambda expression is an anonymous function or simply a method that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read “x goes to x times x.”

The following examples show how to use lambda expressions in C#:

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