I'm trying to learn how C# manages memory. I am stuck on static elements, I read numerous blogs and articles on this subject, but I cannot find a quite satisfactory answer.
Let's define a code block to help find the answer.
class myClass
{
static string myStr = "String Data";
static int myInt = 12;
}
Before you guys share your answer, let me share my findings that I know about this subject. Feel free to agree or disagree and help me to find correct answer.
What confuses me, are some answers that I found on internet, on this subject.
Confusion Number 1:
When your program starts, it loads all the related assemblies into an AppDomain. When the assembly is loaded, all static constructors are called, including static fields. They will live in the there, and the only way to unload them, is to unload the AppDomain.
In above lines, it is mentioned explicitly that all static elements stored on AppDomain. Then why everybody on internet says 'Static' elements are stored on heap/stack?
Confusion Number 2:
Every static variable is stored on the heap, regardless of whether it's declared within a reference type or a value type.
If every static variable stored on heap. Then why some folks says that value type static variable are stored on stack?
Please help to connect my dots to understand memory management of static variables in C#. Thank you very much for your precious time :)
First, note that all of this is an implementation detail. The only thing the runtime guarantees is:
That's pretty much it. Everything else is an implementation detail - the specification doesn't care about stack, heap or anything else. It's up to the implementation of the runtime, and a valid runtime could put everything on the stack, if it so desired, or on the heap. And don't forget registers.
Now, let's see some of the misconceptions you already managed to pick up:
TypeLoadException
, most likely in a method that first references the type (needless to say, this can make debugging statics tricky).Some folks may be confused. Some don't understand the difference between the contract, and the practical implementations. Some simply don't know what they're talking about. I wish there was an easy way to know which is which, but there isn't. If in doubt, you can go to the C#/CLR specifications, but that only tells you about the contract, not the practical reality.
The whole point of managed memory is that you aren't supposed to care about these implementation details. Of course, like any abstraction, it leaks - and it makes sense to know how things really are, down to the CPU micro-intructions, memory caching etc., through all the various layers and abstractions. But it's nothing to rely on - the implementation can change at any time, and it has many times in the past.