简体   繁体   中英

What will be the memory allocation of this C#.NET code

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.

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.

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM