Where will the class be stored if it has a structural variable?

It is already clear that since the structs are value types in c#, they are stored on stack while a class object is stored on the heap (its link, course, stored on the stack).

Warning: (Yes, this may not always be true. Thanks to @Jon for fixing) But in most cases, yes!

But what about a class one of whose member is of type struct ? Now, what will the memory model look like?

By the way, how to check if any object is on stack or heap ?

Good. Some assumptions:

  • This class is local inside the function.
  • A structure is a member not a variable . (Thanks to corrections.)
+6
source share
2 answers

The class itself will be a reference type, so instances of it will be stored on the heap.

The property, which is a struct , is an integral part of the instance (i.e. the object) and therefore will also be stored on the heap, like the int and enum properties of this object,

Note. There will be no references to the struct property, just as there are no references to the int and enum properties.

+6
source

It is already clear that since structures are value types in C #, they are stored on the stack, while a class object is stored on the heap (its reference, cursor, stored on the stack).

This assumption is incorrect. Value types are only included on the stack if they are local variables and are not part of the close / lambda / anonymity method. Even then, they can be put in a heap if the jitter decides.

But what about a class whose variable is a structure type? Now, what will the memory model look like?

The rule above should answer your question: since the type of the value can only be stored on the stack, if it is a local variable, then the class field should go in a heap.

All you need to know about value types: http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx

+2
source

All Articles