Monday 26 December 2016

c# - Object and fields memory allocation

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?.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...