I am using anonymous functions in my projects no less. And till know I was thinking that, C# compiler generates just a method using the code used for the anonymous method in the same class. But, after decompiling this code in IL, I saw that CLR created a new class.
public class Comparer
{
public delegate int Greater(int a, int b);
public int Great(Greater greater, int a, int b)
{
return greater(a, b);
}
}
static void Main(string[] args)
{
int valueOfA = 11,
valueOfB = 23,
valueOfC = 42;
Comparer comparer = new Comparer();
Console.WriteLine("The greater is \t:{0}",
comparer.Great(delegate(int a, int b)
{
int[] numbers = new int[] { a, b, valueOfC };
return Math.Max(Math.Max(a, b), valueOfC);
},
valueOfA, valueOfB));
}
Here is decompiled IL code of the Main method:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 65 (0x41)
.maxstack 5
.locals init ([0] int32 valueOfA,
[1] int32 valueOfB,
[2] class Ch04.Comparer comparer,
[3] class Ch04.Program/'<>c__DisplayClass1' 'CS$<>8__locals2') // Here it is
...
}
If there is nothing to capture it C# compiler will create private method in the class, if you have variables in closure - inner class will be created.
Covered in details in Chapter 12 - Delegates and Lambda Expressions