views:

127

answers:

4
using System;
class ClassOfInts
{
    public int x;
    public int y;
}    

class Test
{
    ClassOfInts objClassOfInts;
    string name;

    public TestMethod(int p, int q, string s)
    {
        objClassOfInts=new ClassofInts;
        objClassOfInts.x=p;
        objClassOfInts.y=q;
        name=s;
    }
}

class Main
{
    static Main()
    {
        Test t1=new Test();
        Test t2=new Test();
        t1.TestMethod(1,2,"First");
        //XXX
        t2.TestMethod(2,3,"Second");
        //YYY
    }
}

What is the memory allocation of above program when it reaches XXX. Will reference variable objClassInts still be reffering to its object in Heap. or As soon as TestMethod finishes Execution, objClassInts will be reffering to null.

+2  A: 

Each instance of Test has its own objClassOfInts instance. That instance will live as long as the Test instance.

In your example, that means they will both live until the end of Main.

BTW, it's a best practice to not use Hungarian notation. In "`objClassOfInts'" we assume it's an object of some kind. Objects aren't special in C# - they're expected.

John Saunders
I completely agree with John regarding the Hungarian notation.
Robert Williams
Thanks, for mentioning about Hungarian notation.
Shantanu Gupta
+1  A: 

I'm not sure I follow the question, but unless you set an object to null, if you still have access to it then the obect will still be there. The benefit of garbage collection is that objects do not surprisingly disappear in some parts of your code,they are only gotten rid of when you couldn't access them anyways.

Chris
A: 

objClassOfInts will not be null. It starts as null, but as long as a Test object is live, all it's referenced objects will also be live.

Steve Cooper
+1  A: 

When execution reaches XXXX, the object referenced by t1 is eligible for garbage collection. Which includes the object references held by its fields, objClassOfInts and name. When it reaches YYYY, both the objects referenced by t1 and t2 are eligible. In debug mode, they won't be eligible until the method exits. It says nothing about when they actually get collected, it can take a while.

Hans Passant