Posted by: R Manimaran | December 10, 2010

Lambda expression and Anonymous methods in C#

Lambda expression and Anonymous methods in C#

A lambda expression is an anonymous function 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.”

Ok Before going to Lambda expression we will first check what is Anonymous functions.

Anonymous methods or function

Anonymous method is a feature introduced in C# 2.0, which allows you to declare your method code inline instead of with a delegate function.

Let us take an example. Suppose you want to create a button that adds an item to a List control we have used like this

this.button1.Click += new System.EventHandler(this.button1_Click);

private void button1_Click(object sender, EventArgs e)
{
 listBox1.Items.Add("Item 1");
}

In C# 2.0 this can be re-written as

this.button1.Click += delegate
{
 listBox1.Items.Add("Item added using Anonymous method");
};

An anonymous method consists of the keyword delegate, an optional parameter list, and a statement list enclosed in { and } delimiters.

The anonymous method in the previous example doesn’t use the parameters supplied by the delegate, and it can therefore omit the parameter list.

To gain access to the parameters, the anonymous method can include a parameter list:

this.button1.Click += delegate(object sender,EventArgs e)
{
  MessageBox.Show(((Button)sender).Text);
};

Advantages:It saves some typing and puts the method closer to where it is being used which helps with maintenance.

public static void AnonymousMethod()
{
List<string> Names = new List<string> { “Chennai”, “Covai”, “Delhi”, “Bangalore” };
// using C# 2.0 Anonymous Method.
string name = Names.Find(FindChennai);
}

public static bool FindChennai(string name)
{
 return name.Equals(“Chennai“) ;
}
public static void InlineAnonymousMethod()
{
List<string> Names = new List<string> { “Chennai”, “Covai”, “Delhi”, “Bangalore” };

//using Inline method in Anonymous
string name1 = Names.Find(delegate(string name)
{
 return name.Equals(“Chennai“);
});
}

Above can be done using Lambda expressions.

public static void UsingLambdaExpression()
{
List<string> Names = new List<string> { “Chennai”, “Covai”, “Delhi”, “Bangalore” };

//using Lamda Expressions
string name = Names.Find((string n) => n.Equals(“Chennai“));
}

Here we are explicitly declare n as string type. we can remove explicitly declaring it and use it simply like this.

public static void UsingLambdaExpression()
{
List<string> Names = new List<string> { “Chennai”, “Covai”, “Delhi”, “Bangalore” };

//using Lamda Expressions
string name = Names.Find(n => n.Equals(“Chennai“));
}

Compared to anonymous methods they provide a very compact and more type-safe way to write small functions that can be passed as arguments for subsequent evaluation.

The parameters of a lambda expression can be explicitly or implicitly typed.

In an explicitly typed parameter list, the type of each expression is explicitly specified.

(int x) => x + 1 // explicitly typed parameter

In an implicitly typed parameter list, the types are inferred from the context in which the lambda expression occurs

(y,z) => return y * z; // implicitly typed parameter

Specify zero input parameters with empty parentheses:

() => SomeMethod(); // zero input parameter

In the Next article we will see some functions which uses the Lambda expressions in SharePoint.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: