Robotronx
Robotronx

Reputation: 1818

Class referencing a struct - allocation

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)?

Upvotes: 1

Views: 65

Answers (1)

canton7
canton7

Reputation: 42235

  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.

Upvotes: 4

Related Questions