Search code examples
.netoopstaticinstancecil

Why does CIL support instances if it is solely stack based


In the Common Intermediate Language (CIL) we can instanciate classes which are not static. That makes a lot of sense if we need to store instance data between method invocations. Why is this necessary in CIL where everything is located on the Stack anyways? There is no instance data stored in CIL, why do I need an instance? Or to blame the compiler: why doesn't the compiler compile every method to be static in CIL? My best guess is that the information of the higher level code can be extracted from CIL. This probably sounds stupid to an experienced CIL programmer because it might be completely wrong, but I am just starting to get into it.

Any clarification is very much appreciated.


Solution

  • The implicit assumption in CIL is that class objects are stored on the GC heap. Accurate at runtime as well. What you get back when you create an object is a reference to the object. A pointer. It takes 4 bytes in 32-bit mode, 8 bytes in 64-bit mode.

    What you do with that pointer is up to your code. You can store it in a local variable (similar to storing it on the stack) or you can store it in a field or static variable. At runtime it is not fundamentally different from an IntPtr, except that the garbage collector can always find it back. Necessary when it moves an object when it compacts the heap, the pointer value needs to be updated. A lot of magic happens under the hood to help the GC to find that pointer back, the just-in-time compiler plays an essential role.

    From the point of view of the runtime, all methods are static. Pretty visible when you write an extension method. What is different between a C# static and an instance method is an extra hidden argument that is passed to the method. You know it well, it is this. A keyword you can always use in an instance method. You don't have to name it yourself in the method's parameter list, the compiler takes care of it. You do name it explicitly in an extension method.