We are always taught and learnt to be that the value types are always stored on the Stack, and this is not true to its entirety. There is this one question which always, from the time I started working on C#, bothered me to ask myself, but until recent time I have never attempted to research to find the reason for it, how shameless of me.
Question: If the value types are used as part of the object instance, where would that be stored, still on the stack?
So the answer to this particular question at least arises one point which contradicts this famous myth. The answer is – Value types are stored on the heap as part of the object instance, not on the stack.
In process of finding the reason, I came across this topic from Eric Lippert, http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx
He says: In the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value.”
Few of other points from his blog:
- There are three types of values: Instances of Value types, Instances of Reference Types and, References
- There are three kinds of storage locations: Stack, heap and registers
- Every storage location has a “life time”. That is, a period of time in which storage location’s contents is valid.
- The time between a start of execution of a particular method and the method returning normally or throwing an exception is the “activation period” for that method execution.
- If the life time of the value is greater than the activation period, then it’s called long lived value, otherwise it is short lived.
- So the choice of the storage location for the complier mostly depends life time of the storage location. How? If the required life time of the storage location is greater than the activation period of the current method execution than the storage is said to be “long lived”, otherwise it is “short lived”
- Long lived storage location are always heap locations.
- Short lived storage location are always stack or registers.
- References and value types are same as far as their storage is concerned: they either on stack or registers or heap, depending whether the storage of the value needs to be short lived or long lived.