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?
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:This code proves your point, output below: