Where Is Memory Allocated When Structs Are Stored in Arrays?
You've probably heard the saying, "Structs in C# are stored on the stack." And on the other hand, arrays are said to be stored on the heap. So that naturally raises a question:
"What happens when a struct is stored in an array? Where does it go?"
This article clears up that exact question.
Structs Are Stored on the Stack by Default
When you declare a struct as a local variable, it is stored on the stack:
void MyMethod()
{
MyStruct s = new MyStruct(); // stored on the stack
}
Value types (like struct
, int
, float
, bool
) are usually stored on the stack, unlike reference types such as class
.
Arrays Are Stored on the Heap (Even Without new
)
In C#, arrays are reference types, so they are always stored on the heap. Even if you omit the new
keyword during initialization, the compiler still allocates memory on the heap internally.
(In C++, arrays can be stored on the stack if declared without new
. This is one of the key differences from C#.)
// stored on the heap
int[] numbers = new int[5];
// also stored on the heap
MyStruct[] segments = new MyStruct[5];
// stored on the heap, even without 'new'
int[] nums = { 1, 2, 3 };
Value Copy to the Heap When Structs Are Added to Containers
Structs are value types, so whether they are initialized with new
or not, they are stored on the stack when declared as local variables.
However, when such a struct is added to a reference type container like an array or a list, it is copied by value and the copy is stored on the heap.
In other words, the original struct does not move to the heap — rather, a separate copy of it is created and stored in the heap.
Once the function ends, the stack-based variable is discarded, but the heap-based copy continues to live as long as the container holds it.
This heap copy remains alive as long as the reference-type container exists, and will only be collected by the garbage collector (GC) when no longer in use.
The key idea: "Even value types are copied into the heap when stored in reference-type containers."
Structs Inside a Class Are Also Stored in the Heap
Classes are reference types, so they are stored on the heap. If a class contains a struct field, that struct becomes part of the class instance.
Unlike arrays or lists, the struct here is not copied from the stack to the heap — instead, it is allocated directly as part of the class's memory on the heap.
class MyClass
{
// This struct is stored as part of the MyClass instance on the heap
public MyStruct segment;
}
Summary
Structs are typically stored on the stack when declared locally. However, when added to an array or list, a value copy is made and stored on the heap.
Also, when a struct is part of a class, it is not moved or copied but is simply included within the heap memory of the class instance.
Value types can also live in the heap — that's a key takeaway when understanding C#’s memory model.