1
class Foo
{
    public Bar StructProperty { get; set; }
    public int IntProperty { get; set; }
}

struct Bar
{
}

Let's assume I have a class that has a struct property. I do a var foo = new Foo(). How is foo.StructProperty laid out in memory? Is it:

  1. Boxed on the heap or
  2. Contained within the heap address space belonging to the foo object itself (just like foo.IntProperty is laid out)?
Robotronx
  • 1,728
  • 2
  • 21
  • 43
  • 2
    #2. It's on the heap, same space as the class itself. – Zer0 Apr 07 '20 at 13:39
  • maybe this can help you understand it better: https://stackoverflow.com/questions/203695/does-using-new-on-a-struct-allocate-it-on-the-heap-or-stack – vhr Apr 07 '20 at 13:42

1 Answers1

4
  1. Contained within the heap address space belonging to the foo object itself (just like foo.IntProperty is laid out)?

This is correct.

The mantra "structs are allocated on the stack, classes are allocated on the heap" is misleading here -- structs which are part of other objects (other classes or structs) are stored inside the memory used for those objects. An int is no different to any other struct type in this respect.

canton7
  • 37,633
  • 3
  • 64
  • 77
  • Very misleading I would say. Vice versa can happen with `stackalloc`, for example. – Zer0 Apr 07 '20 at 13:43
  • @Zer0 Care to expand on that? You can't allocate a class on the stack using stackalloc. You can allocate what is effectively an array (although it isn't actually an array -- you can only refer to it using a pointer or a `Span`). – canton7 Apr 07 '20 at 13:44
  • Sure can. You can use `unsafe` and `stackalloc` and pointers. You're really only limited by space. – Zer0 Apr 07 '20 at 13:46
  • 1
    @Zer0 Can you give me an example of allocating a class on the stack using stackalloc? Unless you're referring to [this](https://blog.adamfurmanek.pl/2016/04/23/custom-memory-allocation-in-c-part-1/)... – canton7 Apr 07 '20 at 13:46
  • Does [this](https://blog.adamfurmanek.pl/2016/04/23/custom-memory-allocation-in-c-part-1/) work for you? I guess I should say unless you're doing crazy things (like we do in trading) classes are usually on the heap. Which we avoid like the plague. – Zer0 Apr 07 '20 at 13:50
  • Ah right, the same link I found. That's not really allocating an object on the stack -- that's copying an object to the stack. It's not really something that's supported in any way though -- you can do practically anything if you start messing around with `__makeref` and the internal representation of objects. Point taken, though, thanks – canton7 Apr 07 '20 at 13:52
  • Not the way they do it sure. But there's also `_asm`, unmanaged memory, etc... There's plenty of ways to get around the heap if you want to. We do it all the time. I guess I should keep the fringe methods out of comments. Point taken. But more importantly, a value type is definitely not guaranteed to be on the stack. I cringe when I hear that. – Zer0 Apr 07 '20 at 13:54