Skip to main content

Antonio Cisternino's Home Page

Go Search
Antonio Cisternino's Home Page > My Blog > Again on closures  

My Blog: Again on closures


Again on closures 


Roshan has posted again (,guid,81e20e21-6ec6-4fed-9c89-a5b77d21aec6.aspx) on closures on C# and CLR 2.0. I suggest you to read the following posts to keep up with the thread:
Roshan poses an interesting problem about the this pointer that may part of the environment of a closure. As he notes if two classes A and B build a closure with the same values but referring the this pointer, the environment cannot be shared.
Again with CLR2.0 you may rely on Generics to have a generic environment letting the runtime instantiate closure as needed within the runtime. Because of generics implementation you get more efficient code because the runtime shares instatiations of generic classes with reference type parameters.
In general we may think that the compiler generates several environment classes, for the needed arities; for instance:
class Environment3<A, B, C> {
  A a;
  B b;
  C c;
In this case the Environment3 class represents all the possible environments with three entries.
Another issue that it may arise from mapping closures on extended delegates is the interaction with reflection. In the current implementation of anonymous methods, C# declares the class containing the environment as private. This means that the anonymous method has access to private members of the class. Besides, if the compiler relies on CLR 2 delegates, and the environment class is declared outside the class defining the anonymous method the access to private members becomes impossible.
Moreover it is possible to access the reference to the environment closed into a delegate by means of reflection. This may allow classes outside the assembly to access the environment of a class potentially introducing security issues.
Of course it is possible to think of a compiler that degrades gracefully trying to avoid classes unless necessary. Nonetheless it would be better to find translation schemas that avoid the generation of unneeded classes.
A good approximation to protect the environment of a closure can be to limit the scope of the environment class to the the assembly. Thus outside the assembly the environment would become inaccessible.
A similar trick can be used to expose private members of a class to an environment class declared outside of it: private members can be used outside through an internal interface (exploiting the ability of specifying implementations for interfaces provided by C#).




Created at 5/31/2004 22:09  by Antonio Cisternino 
Last modified at 5/31/2004 22:16  by Antonio Cisternino