Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where will the class be stored if it has a struct variable?

Tags:

c#

.net

c#-4.0

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:

  1. This class is local inside a function.
  2. The struct is a member not a variable. (Thanks to the corrections.)
like image 719
now he who must not be named. Avatar asked Dec 10 '13 09:12

now he who must not be named.


2 Answers

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.

like image 104
Roy Dictus Avatar answered Nov 08 '22 17:11

Roy Dictus


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

like image 28
dcastro Avatar answered Nov 08 '22 19:11

dcastro