It is not a duplicate, I would like to know about this in context of C#.
I have such classes:
public class A
{
public List<string> AList { get; set; }
}
public class B
{
public List<string> BList { get; set; }
}
Imagine, that in row 6
happens Garbage Collection:
1 row: A objectA = new A();
2 row: B objectB = new B();
3 row: objectA.AList = new List<string>() { "1", "2", "3" };
4 row: objectB.BList = objectA.AList;
5 row: objectA = null;
6 row: //Garbage collection occurs
I have two questions:
Will be objectA
garbage collected? If yes, why? Cause, in my view these objects will be created in a heap like in the following image:
My second question is whether the following image is correct about how objects will be allocated in a heap. I mean, is objectA.AList
placed inside a circle(the above image) or near the circle(the following image):
Yes, the variable that objectA
refers to will be - or at least may be garbage collected. There's nothing referring to it any more. (There's no guarantee that it will collected "soon", but it's eligible for garbage collection.)
The list that objectA.AList
referred to won't be garbage collected, because objectB.BList
now refers to it.
The problem with your first diagram is the idea that one object is "inside" another. That's not how it works - an object just maintains a reference to another, but each object is effectively an independent piece of memory... and if there are no references from anything to a particular object, it's eligible for garbage collection.
See more on this question at Stackoverflow