Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't see how the compiler uses the classes he creates for my closures

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++;
    };
}
like image 587
Christoph Avatar asked Oct 10 '22 13:10

Christoph


1 Answers

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.

like image 198
Jon Skeet Avatar answered Oct 17 '22 23:10

Jon Skeet