Hi Folks,
I wanted to know how a simple lambda expression looks like when reflected in .NET.
So I wrote this Xunit test class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Xunit;
namespace LambdaTutorials
{
public class TestClass
{
delegate int del(int i);
[Fact(Timeout=50000)]
static void SampleLambda1()
{
int expectedValue = 25;
del myDelegate = x => x * x;
int j = myDelegate(5);
Assert.Equal(j, expectedValue);
}
}
}
Then, using TestDriven.NET and Red Gate's .NEt reflector (too lazy to reflect myself. I see this as the generated code for the method.

What I find cool is how the lambda expression was generated. It is just a normal delegate behind the scenes.
Also, I wanted to see how the implict var is handled when converting to int. Again it detected the int :)
[Fact(Timeout = 50000)]
static void SampleLambda1()
{
var expectedValue = 25;
del myDelegate = x => x * x;
int j = myDelegate(5);
Assert.Equal(j, expectedValue);
}

I think this is a really usefull way of seeing complex lambda expression behave, by using the reflector tool, you can then see Linq or any other code that users lambda to generate the more rudimentry code, which could help when you lost with => all over the place!
In fact, lets write a Linq expression and see how the lambda expressions pan out!!!
Lets take an old school function to count the number of times is sees a 2.
[Fact(Timeout = 50000)]
public void GetCountOfNumbersInListOldSchool()
{
int value = 2;
List<int> myList = new List<int>() { 1, 2, 3, 4, 5, 2, 1 };
int total = 0;
foreach (int item in myList)
if (item == value)
total++;
Assert.Equal( total,2);
}
The reflect code from the above looks like this:

Now, lets use lamba/linq and make the code above more elegant, a one liner :)
[Fact(Timeout = 50000)]
public void GetCountOfNumbersInList()
{
int value = 1;
List<int> myList = new List<int>() { 1, 2, 3, 4, 5, 2, 1 };
Assert.Equal( myList.Count(item => item == value), 2);
}
code generated from Lambda is:

From the above, we can see, that Lambda is basically just another way of injecting delegates, and in this case it is just an anonymous method!
See this:
delegate (int item) {return item == value;}
is the same as:
item => item == value)
Thats all it is!! Lambda justs makes queries look cool :)
Lets put them together
item => item == value)
delegate (int item) {return item == value;}
Item is mentioned twice => is just a way to declare a delegate for code block execution aka "Anonymous methods".
Happy Lambda, now that we have deeper insite into what code it generates in the background.