How can I prove that boxing causes the variable to be stored on the heap instead of the stack?

How can I prove that boxing causes the variable to be stored on the heap instead of the stack?

boxing

I want some code to show my students that boxing causes the variable to be stored on the heap instead of the stack.

Boxing and Unboxing

+4
source share
1 answer

It is surprisingly difficult to distinguish between heaps and stack objects (which is intentional because .NET wants to hide this information from programmers).

One approach you can take is to compare the default default address hash codes in the marked objects and watch them 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));
    }
}

, MakeBoxed, , MakeBoxed . , Main, , (- ).

0

Source: https://habr.com/ru/post/1668858/


All Articles