65.9K
CodeProject is changing. Read more.
Home

Using Lambda Expression in C# 3

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.37/5 (12 votes)

Apr 3, 2008

CPOL

1 min read

viewsIcon

30799

This article describes how to use Lambda expression in C# 3 to make developers' life easier.

Introduction

Lambda expressions provide a more concise, functional syntax for writing anonymous methods.

Why Lambda Expressions

For better understanding about Lambda expression, let’s look at anonymous methods which are not new to C# 3.0 but are available from C# 2.0 itself. Anonymous methods mean code blocks can be written in-line where delegate values are expected. Somehow this anonymous method syntax is little bit difficult on functional programming and this is the point where lambda expressions come into action in C# 3.0.

Using Lambda Expressions

A lambda expression is written as a parameter list, followed by the => token, followed by an expression or a statement block.

( parameters ) => expr

Example

  • i => i + 1; 
  • i => { return i + 1; } 

We can read this lambda expression as “goes to” so the above example can be read as “x goes to x+1”.

Note that here, we do not provide parameter types. If you need, you can define types also but nothing else adds more readability to your coding than a little more typing.

We can use multiple parameters also:

  • (i,j) => i + j;

Or even no parameters at all, like this:

  • () => Console.Write("Hi Lambda"); 

Example

So now that you have a basic idea about Lambda expressions, it’s better to move on to a few more examples:

Func<int, int> f1 = x => { return x + 2; };

Console.WriteLine(f1(1));

Produces the output: - 3.

As I mentioned first this is actually nothing more than an anonymous method, so this can be written in as:

Func<int, int> f1 = delegate(int x) { return x + 2; };

Console.WriteLine(f1(1));

Produces the output: - 3.

Example

We can even write methods of several lines, although it is not what we expecting by using Lambda expression, it is possible to write and is perfectly correct.

Func<int, double, string, int> f4 = (x, y, z) => 
{ 
    int i_1 = x; 
    int i_2 = Convert.ToInt32(y); 
    int i_3; 
    if (!int.TryParse(z, out i_3)) 
        return -1; 
        return i_1 + i_2 + i_3; 
}; 
Console.WriteLine(f4(1, 2.0, "3"));

Example

Another useful example:

button1.Click += (s, ea) => MessageBox.Show("Hi");

Conclusion

Here I have given you an introduction and some examples where Lambda expression becomes helpful, easy to use. C# 3.0 has made developers' life more easy.

History

  • 3rd April, 2008: Initial post