Stack & Heap & Garbage Collector

581 views Asked by At

The title might be a bit incorrect however its about Stack & Heap and Garbage Collector none the less.

My Code:

    static void Main(string[] args)
    {
        MyInt x = new MyInt();
        x.MyValue = 3;
        MyInt y = new MyInt();
        y = x;
        y.MyValue = 4;
        Console.Read();
    }

    public class MyInt
    {
        public int MyValue;
    }

My Question:

Am I understanding this correct that at first y was created with its pointer to new MyInt in memory and then y pointer was replaced by x pointer and now y points to same object(its called object right?) as x in memory?

AND that y's object now that was created before now left on the heap with out any pointer to it? That it exist on the heap but no one points to this object in memory. And that now this object is subject for Garbage collector?

Am I getting this correct?

2

There are 2 answers

0
Baldrick On BEST ANSWER

Yes, you're right. And the nice thing is you can prove it by using a WeakReference.

A WeakReference is an object which tracks another reference, but without preventing it from being collected. This allows you to check your target reference any time, and see if it has been collected yet:

private static void Main(string[] args)
{
    MyInt x = new MyInt();
    x.MyValue = 3;
    MyInt y = new MyInt();
    WeakReference reference = new WeakReference(y);
    Console.WriteLine("Y is alive: " + reference.IsAlive);
    y = x;
    y.MyValue = 4;
    Console.WriteLine("Y is still alive: " + reference.IsAlive);
    Console.WriteLine("Running GC... ");
    GC.Collect(2);
    GC.WaitForFullGCComplete();
    Console.WriteLine("Y is alive: " + reference.IsAlive);
    Console.Read();
}

This code proves your point, output below:

Y is alive: True
Y is still alive: True
Running GC...
Y is alive: False
0
dcastro On

Yes, your interpretation is correct. At first, variables x and y point to different values - a and b respectively. Then they point to the same value a. Therefore, there are no strong references to b, so it can be elected for garbage collection.