It is already clear that since the structs are value types in c#, they are stored on stack
whereas a class object is stored on the heap
(its reference, of-course stored on stack).
Warn: (Yes, this might not always be true. Thanks to @Jon for correction) But in most cases, yes!
But, what abouta class one of whose member is of type struct
? Now, how will the memory model be?
BTW, how do I check if some object resides in stack
or heap
?
Okay. Some assumptions:
member
not a variable
. (Thanks to the corrections.)The class itself will be a reference type, so instances of it will be kept on the heap.
The property that is a struct
is an integral part of the instance (i.e., of the object), and so will also be kept on the heap, just like the int
and enum
properties of that object.
Note: There will be no references to the struct
property, just like there are no references to the int
and enum
properties.
It is already clear that since the structs are value types in c#, they are stored on stack whereas a class object is stored on the heap (its reference, of-course stored on stack).
That assumption is incorrect. Value types only go on the stack when they're local variables, and are not part of a closure/lambda/anonymous method. Even then, they may be put on the heap if the jitter decides to.
But, what abouta class one of whose variable is a struct type ? Now, how will the memory model be?
The rule above should answer your question: since a value type can only be stored on the stack if it's a local variable, then a class's field must go on the heap.
Everything you need to know about value types: http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With