Lambda's and Anonymous functions in C# 3.5

Here’s a lambda function in use with the new extensions for a List object.

personnel.foreach(x => x.DoSomeCoolStuff());


Lambdas are sort-of minified anonymous functions (which are also new), they are limited (correct me if im wrong) in that they can execute one statement as above.
They can even be use as below:

Action<int> addone = x => x+1;
Console.WriteLine(addone(2)); 
//Outputs: 3

Or if you want to have some more functionality, use an anonymous function:

Func<int, int> doMagic = delegate(int x)
   {
       var magic = MagicFactory.MakeMagic();
       return magic.process(x);
   }
Console.WriteLine(doMagic(2)); 
//Outputs: 8

Every now and then Microsoft gets something right :)

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *