Geeks With Blogs

News
Michael Crump Microsoft MVP, INETA Community Champion and XAML Advocate.

The purpose of my blog is to explain things for a Silverlight developer. One of the best things about Lambda's is that you not only use them in Silverlight but any project targeting .net 3.5 I’ve seen several blog post that use lambda expressions always assuming the audience is familiar with them. The purpose of this post is to make them simple and easily understood. Let’s begin with a 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.

So anonymous function… delegates or expression tree types? I don’t get it??? Confused yet?

image

 

Lets break this into a few definitions and jump right into the code.

anonymous function – is an "inline" statement or expression that can be used wherever a delegate type is expected.
delegate - is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value.
Expression trees - represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

 

Don’t worry if this still sounds confusing, lets jump right into the code with a simple 3 line program. We are going to use a Function Delegate (all you need to remember is that this delegate returns a value.) Lambda expressions are used most commonly with the Func and Action delegates, so you will see an example of both of these.

Lambda Expression 3 lines.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication7
  7. {
  8.     class Program
  9.     {
  10.          static void Main(string[] args)
  11.         {
  12.             Func<int, int> myfunc = x => x *x;
  13.             Console.WriteLine(myfunc(6).ToString());
  14.             Console.ReadLine();
  15.         }
  16.  
  17.     }
  18. }

Is equivalent to

Old way of doing it.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication7
  7. {
  8.     class Program
  9.     {
  10.          static void Main(string[] args)
  11.         {
  12.  
  13.             Console.WriteLine(myFunc(6).ToString());
  14.             Console.ReadLine();
  15.         }
  16.  
  17.          static int myFunc(int x)
  18.          {
  19.              return x * x;
  20.  
  21.          }
  22.  
  23.     }
  24. }

In the example, there is a single parameter, x, and the expression is x*x.

I’m going to stop here to make sure you are still with me. A lambda expression is an unnamed method written in place of a delegate instance. In other words, the compiler converts the lambda expression to either a :

  • A delegate instance
  • An expression tree

All lambda have the following form:

(parameters) => expression or statement block

Now look back to the ones we have created. It should start to sink in. Don’t get stuck on the => form, use it as an identifier of a lambda.

A Lamba expression can also be written in the following form:

Lambda Expression.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication7
  7. {
  8.     class Program
  9.     {
  10.          static void Main(string[] args)
  11.         {
  12.             Func<int, int> myFunc = x =>
  13.             {
  14.                 return x * x;
  15.             };
  16.  
  17.             Console.WriteLine(myFunc(6).ToString());
  18.             Console.ReadLine();
  19.         }
  20.  
  21.     }
  22. }

This form may be easier to read but consumes more space.

Lets try an Action delegate – this delegate does not return a value.

Action Delegate example.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication7
  7. {
  8.     class Program
  9.     {
  10.          static void Main(string[] args)
  11.         {
  12.             Action<string> myAction = (string x) => { Console.WriteLine(x); };
  13.             myAction("michael has made this so easy");                      
  14.             Console.ReadLine();
  15.         }
  16.  
  17.     }
  18. }

 

Lambdas can also capture outer variables (such as the example below)

A lambda expression can reference the local variables and parameters of the method in which it’s defined. Outer variables referenced by a lambda expression are called captured variables.

Capturing Outer Variables
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication7
  7. {
  8.     class Program
  9.     {
  10.          static void Main(string[] args)
  11.         {
  12.             string mike = "Michael";
  13.             Action<string> myAction = (string x) => {
  14.                 Console.WriteLine("{0}{1}", mike, x);
  15.          };
  16.             myAction(" has made this so easy");                      
  17.             Console.ReadLine();
  18.         }
  19.  
  20.     }
  21. }

Lamba’s can also with a strongly typed list to loop through a collection.

 

Used w a strongly typed list.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication7
  7. {
  8.     class Program
  9.     {
  10.          static void Main(string[] args)
  11.         {
  12.             List<string> list = new List<string>() { "1", "2", "3", "4" };
  13.             list.ForEach(s => Console.WriteLine(s));
  14.             Console.ReadLine();
  15.         }
  16.  
  17.     }
  18. }

Outputs:

1

2

3

4

I think this will get you started with Lambda’s, as always consult the MSDN documentation for more information. Still confused? Hopefully you are not.

image

Posted on Sunday, April 25, 2010 5:03 PM General C# | Back to top

Copyright © mbcrump | Powered by: GeeksWithBlogs.net