Reputation: 81
It is common knowledge that a struct is a value type, and is therefore allocated on the stack but when struct has class reference then it will stored on Stack or Heap.
public class A {
public int Value { get; set; }
}
struct Rectangle
{
public int width;
public int height;
public A a;
}
static void Main(string[] args)
{
Rectangle r ; // r will create on stack
r.width = 5; // it will create on stack as well,
r.a = new A(); // but what about A object, it will stored on stack or heap, as i know class object it stored on heap, now it is inside the struct.
}
I know it is very common question, I have google it, didn't find right answer. Thanks for in advance
Upvotes: 0
Views: 1272
Reputation: 36361
struct is a value type, and is therefore allocated on the stack
This is incorrect. A more correct statement would be "value types can be stored on the stack", see the truth about value types. The value type will probably be stored on the stack if given as a parameter, even if the jitter if free to store it wherever it damn pleases. But if the struct is part of a class, it will be stored on the heap, with all the other fields of the class.
Now, the reference to A will be stored as part of the struct, i.e. 8 bytes on x64. But the actual object it points to, including the int Value
, will be stored on the heap.
Upvotes: 3