How can I prove that boxing cause storing a variable in heap instead of stack?
I want some code to show my students that boxing cause storing a variable in heap instead of stack.
It is surprisingly hard to distinguish between heap and stack objects (which is intentional, because .NET wants to hide this implementation detail from programmers).
One approach you could take is to compare address-based default hash codes of boxed objects, and observe that they keep changing (demo):
static object MakeBoxed() {
int n = 5;
object a = n;
return a;
}
public static void Main() {
for (int i = 0 ; i != 10 ; i++) {
object a = MakeBoxed();
Console.WriteLine(RuntimeHelpers.GetHashCode(a));
}
}
Objects created inside MakeBoxed
cannot be on the stack, because the stack frame of MakeBoxed
is deactivated after the call. Further, they cannot be in the stack frame of Main
, because stack frames do not grow, yet all objects have different addresses (default hash codes).