Friday, January 14, 2011

C# Lambda Expression

Lambda Expressions have been part of .NET since version 3.5 (C# 3.0); so, I decided to add a quick tutorial to the blog for programmers new to C# or C# 3.0+.

Quick Definition
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
From MSDN Site

In sum, a lambda expression is a way we can implement an anonymous method in less code. Besides the syntactic benefits added by Lambda expression; they also bring elements of functional programming into C# (a traditional object oriented language).

To the point

A lambda expressions must being with a parameter or set of parameters followed by the lambda symbol (=>) then the expression to be executed.

Syntax Form:
Parameter(s) => Expressions
Example 1:
X => X * 2
The example shows a function where X is the parameter following by the return expression of (X * 2).

Example 2:

Let’s declare a delegate.
public delegate int DoubleIt(int v);

Back in C# 2.0 we would have to use an anonymous method (see example below):
DoubleIt d = new DoubleIt(delegate(int x) {
     return x * 2;
 });
Console.WriteLine(d(3));

We can still use an anonymous methods; however, we can also use lambda expressions to accomplish the same thing (see example below):
DoubleIt d =  x => x * 2;
Console.WriteLine(d(3));



Example 3:
Lambda expression with multiple arguments

Let’s declare a delegate.              
public delegate int Multiply(int a, int b);
Multiply multi = (a, b) => a * b;

Console.WriteLine(multi(2, 3));

Lambda Statements

Lambda statements follow the same principle as expression; but, it encloses a full statement within brackets.

Syntax Form:
Parameter(s) => { Statement }
Example 4:
X => { Return  X * 2; }

Example 5:
Lambda statement that returns void

Let’s declare a delegate.
delegate void Greeter(string name);

...

Greeter g = new Greeter((string name) => {
                Console.WriteLine("Hello " + name);
            });
g("Walter");

Or
Greeter g = name => { string r = "Hello " + name; Console.WriteLine(r); };
g("Walter");

Output:
Hello Walter



Summary
The purpose of this post was to show you a basic implementation of lambda expressions in C# via examples without touching the functional programming subject. 

No comments:

Post a Comment