Reference type variables themselves are stored on the stack, is that correct?
While we often say value types live on the stack, ref types live on the heap.
That's not completely true right?
1. eg. Building house = new Building();
In this case, house is simply a pointer to the building object. And it's stored on the stack. While actual building object is stored on the heap.
2. When we assign int to a List<int>, those int values actually live on the heap. ( Of course if we create int variables directly, they are stored on the stack)
Is this the correct interpretation?
5 Replies
Also is this why we don't have boxing/unboxing with List<int>, because those ints are stored directly on the heap ( albeit inside the List array )
Generics are not boxed by default indeed
What do you mean by " if we create int variables directly, they are stored on the heap" in 2.? Local variables are on the stack. If the variable is of a reference type, the object is on the heap while the local reference on the stack
I am actually so happy this question came up, busy with this now:
When you declare a reference type variable such as
Building house
, the variable house itself is indeed stored on the stack. However, if you initialize it using new, as in house = new Building()
, the object it refers to is stored on the heap.
Value types, like int
, float
, struct
, etc., are typically stored on the stack when they are local variables within a method or function. However, if they are part of an object (whether a reference type object or a value type object), they are stored along with that object. Reference types, such as classes and interfaces, are usually stored on the heap.
So yes, you are right, the above is to just clarify the diff. between value types and reference types
It's also worth noting that reference objects may be stored on the stack but the data it is storing, if there is any, could be stored on the heapCases of boxing are for when a reference may be a value or reference type. The reference can be passed around but if the reference were to be to a value on the stack, the reference could become invalid, rendering the language not memory-safe. This is resolved by copying the value to the heap.
To be distinguished with passing by
ref
, where the reference remains valid for the lifetime of the call so it can safely pass references to the stack
Although there's also the odd case of ValueType
which seems to also involve boxing as the actual type (and importantly size) can vary at runtime even if it can only store value types. Similar deal with Enum
as enums can have different underlying types.Sorry it was a typo, I meant
if we create int variables directly, they are stored on the stack