Hi I have some doubts in the memory allocation of the reference types.Please clarify my questions that are commented in between the code below.
class Program
{
static void Main(string[] args)
{
testclass objtestclass1 = new testclass();
testclass objtestclass2 = new testclass();
testclass objtestclass3 = new testclass();
// Is seperate memory created for all the three objects that are created above ?
objtestclass1.setnumber(1);
objtestclass2.setnumber(2);
Console.Write(objtestclass1.number);
Console.Write(objtestclass2.number);
objtestclass3 = objtestclass1;
//When we assign one object to another object is the existing memory of the objtestclass3 be cleared by GC
Console.Write(objtestclass3.number);
objtestclass3.setnumber(3);
Console.Write(objtestclass3.number);
Console.Write(objtestclass1.number);
Console.Read();
}
public class testclass
{
public int number = 0;
public void setnumber(int a)
{
number = a;
}
}
Thanks.
The instance of
testclassis on the heap. Each instance will consist of:numberOn a 32-bit Windows .NET, this will take 12 bytes.
The local variables within the
Mainmethod (objtestclass1etc) will be on the stack – but they’re references, not objects. Each reference will be 4 bytes (again on a 32-bit CLR).The difference between references and objects is important. For example, after this line:
You’re making the values of the two variables the same – but those values are both references. In other words, both variables refer to the same object, so if you make a change via one variable you’ll be able to see it via the other variable. You can think of the reference as a bit like a URL – if we both have the same URL, and one of us edits the page it refers to, we’ll both see that edit.
For more information on this, see my article on reference types and another one on memory.