0

Suppose we have the following code:

void method() {
    int[] test = new int[3];
    test[0] = 0;
    test[1] = 1;
    test[2] = 2;
}

From what I read from Jon Skeet's post on SO, the new int[3] part is equivalent to:

public class ArrayInt3 {
    public readonly int length = 3;
    public int value0;
    public int value1;
    public int value2;
}

So does that mean test (a reference to ArrayInt3) is on the stack? And does that mean ArrayInt3 is on the heap? And I suppose value0, value1, and value2 are on the heap as well (i.e. 0, 1, 2 in this example)?

So in total, there is 4 objects on the heap, correct?

0

1 Answer 1

1

There will be no object on the stack. On the stack, there will be a reference value to the single int[] object stored in the heap.

You have to start making the distinction between objects, variables, and values.

Local variables are part of the method stackframe, which is on the stack. So the reference value to the int[] will be stored in the variable, on the stack.

Sign up to request clarification or add additional context in comments.

8 Comments

@SomeRandomGuy Those are not objects. First, ArrayInt3 is a type. The rest are values. They are part of the single int[] object. They are not independent.
@SomeRandomGuy If they were initialized, they would be 4 reference values pointing to 4 other objects on the heap.
@SomeRandomGuy No, there is a single object on the heap, the int[] object.
Assuming value0, value1, and value2 are initialized, then what do we have on the heap exactly? value0, value1, value2, and ArrayInt3, right? I apologize for asking this poorly.
@SomeRandomGuy You'll have memory allocated for an instance of type ArrayInt3. That memory will be large enough to fit exactly those fields and their value.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.