How closures are implemented by .Net

Hello everybody,

today I want to share piece of wisdom which is interesting, but hard to explain why somebody may need it. That is how closures are implemented. 

Consider the following code:

Snippet

class Program
    {
        static void Main(string[] args)
        {
            int a = 54;
 
            Task t = new Task(
                () =>
                {
                    a++;
                    Console.WriteLine("Inside task");
                }
                );
            t.Start();
 
        }
    }

Now you may wonder, how a will be passed to closure? How Console.WriteLine will be executed?

For my surprise .Net for closures generates behind the curtains the whole class. And instead of all referencing to variable a, it substitutues it by referencing to member of class.

Take a look at the following screenshot:

The class c__DisplayClass0_0 was generated by .Net compiler. And take note that it has variable a, which is of type int32. 

Also, if to double click on Main with letter S following will be opened ( just without highlighting )

and take note, instance of which class was created? c__DisplayClass0_0 !!!!

And that class was passed to every place, where it is needed to do something with variable a. 

Question, does generated class has only variable a? 

Take note at another screenshot:

.Net generated in class c__DisplayClass0_0 method, and inside of that method is used Console.Writeline with input paramether as string.

No Comments

Add a Comment