I wrote this very basic programm to examine what the compiler is doing behind the scenes:
class Program
{
static void Main(string[] args)
{
var increase = Increase();
Console.WriteLine(increase());
Console.WriteLine(increase());
Console.ReadLine();
}
static Func<int> Increase()
{
int counter = 0;
return () => counter++;
}
}
Now when I look at the code with Reflector I do see that the compiler generates a class for my closure like that:
[CompilerGenerated]
private sealed class <>c__DisplayClass1
{
// Fields
public int counter;
// Methods
public int <Increase>b__0()
{
return this.counter++;
}
}
That's fine and I'm aware that he needs to do that to handle my closure. However, what I can't see is how he is actually using this class. I mean I should be able to find code that instantiates "<>c__DisplayClass1" somewhere, am I wrong?
EDIT
If I click on the increase method it looks like that:
private static Func<int> Increase()
{
int counter = 0;
return delegate {
return counter++;
};
}
You should find it in the Increase
method, which I'd expect to have an implementation along these lines:
// Not actually valid C# code because of the names...
static Func<int> Increase()
{
<>c__DisplayClass1 closure = new c__DisplayClass1();
closure.counter = 0;
return new Func<int>(closure.<Increase>b__0);
}
Reflector won't show you that code unless you turn off its optimization, but it should be there. Either turn off Reflector's optimization, or use ildasm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With