views:

47

answers:

2

Hi, it's being a long time since i'm trying to find out the truth about static classes. my point is: value types are allocated in stack, reference types in heap, when using the new operator. but a nature of a static class is that you can't make an instance of it, and sure it's not a value type. so i have a question when and where does the CLR allocates a memory for static content? about when...i'm supposing during compilation, when an assembly is built, but i'm not sure. and about where...while i was trying to find out i read J.Richter's "CLR via C#", and he wrote, that static method of an instance-class is allocated in heap when you're creating an instance of that specific class(together with type object pointer and sync block index). but i don't get it. it's static. it shouldn't depend on any state of object. so please, lighten me.

+1  A: 

As well as user heap memory, the CLR keeps various bookkeeping information & metadata on the heap. This includes the actual code for methods you execute, as well as a Type object for every type loaded into the AppDomain - it's name, overloads, whether it's abstract or sealed, and a list of all the methods (both static and instance) defined on the type.

When you execute a method, the CLR looks up the method information in the corresponding Type object on the CLR-only part of the heap and executes that method. The only difference between instance and static methods is that instance methods include an extra 'this' pointer in the method arguments pointing to the instance the method is executing on.

So, the static information is stored on the heap along with everything else, but it is not associated with any particular object instance.

thecoop
yeah, that makes a good sense! thank you! so, all this instance-and-static classes thing looks deceptive. it's just an extra "this" pointer, but it's all kept in same place...same way. thanks very much
Mark
+2  A: 

The CLR maintains several heaps associated with an AppDomain, collectively called "loader heaps". They are distinct from the garbage collected heap since they don't contain collectable objects, mostly type related data. The kind of data that's around for the lifetime of an AppDomain.

Space for static variables is allocated in one of them, the HighFrequencyHeap. The JIT compiler makes the allocation, the code it generates directly references the memory location. Background info is in this MSDN Magazine article.

Hans Passant