0

I just need a simple clarification of memory allocation of an object

Lets say I have the following class:

public class Test
    {
        public int a;

        public Test(int A)
        {
            a = A;
        }
    }  


////Main program


Test test1 = new Test(32);

Test test2 = test1;
test2.a = 5;

Print(test1.a.ToString());// output =5
Print(test2.a.ToString());// output =5

My question is:

I know that value types are allocated in the stack and that reference types are allocated in the heap. But when an object is created and it has a value type field, were would the field be allocated?. When I create a copy of test1 and assign it to test2 both objects are pointing to the same memory location, would this mean that int a has only one copy in the stack and that's why both objects have the same output of 5?.

  • "value types are allocated in the stack" is just not true. – H H Mar 03 '19 at 17:25
  • [Here's an article by Eric Lippert on why Henk is correct](https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/) – Jlalonde Mar 03 '19 at 18:03

1 Answers1

0

In this situation, where a reference type has a value type. It gets saved into the heap space of the object. If you think about it, it's actually very similar to how objects store references to other objects. There is an allocated amount of space within the space allocated for the value within the object.

The reason both your objects printed the same is because you have two variables referencing the same object in memory. When we reference the objects int a we're going to the value of A's location from the objects reference. Because both variables point to the same reference, the location of a is the same location in memory, and thus the same value

Jlalonde
  • 483
  • 4
  • 13