Reputation: 39
I have a question about C# memory management. Imagine I have a simple class that has three StringBuilder objects:
public class A
{
public StringBuilder sbOne = new StringBuilder();
public StringBuilder sbTwo = new StringBuilder();
public StringBuilder sbThree = new StringBuilder();
}
And another simple class that has one StringBuilder object:
public class B
{
public StringBuilder sb;
public B()
{
A a = new A();
sb = a.sbOne;
}
}
As you can see class B creates a new instance of class A in it's constructor, and assigns it's StringBuilder field to a.sbOne. How is memory freed in this situation? Are a.sbTwo and a.sbThree eligible for garbage collection since there are no references to them, nor are there any references to a? Or are they kept in memory since they are apart of a, whose sbOne field is still referenced?
EDIT: edited to change DateTime to StringBuilder since DateTime is a struct and I was assuming it was a class.
Upvotes: 2
Views: 363
Reputation: 6613
If an object of type A
is created, none of it's properties/fields are eligible for collection, as long as the object is not eligible for collection. For example:
A a = new A();
until there is no reference to a
, none of a.sbOne
, a.sbTwo
and a.sbThree
can't be collected.
In your second example:
public class B
{
public StringBuilder sb;
public B()
{
A a = new A();
sb = a.sbOne;
}//when this is reached the entire object a is eligible for collection
}
And even if a
can be collected, the reference held by sb
in the B
class object will not be affected, because the object of type B
will be entirely separated from a
.
Upvotes: 3
Reputation: 35270
a
will be garbage collected along with its fields a.sbTwo
and a.sbThree
as soon as the constructor B()
exits. The instance referred to by a.sbOne
and sb
in your B
instance will remain until your B
instance is garbage collected itself, or you set sb
to another instance or to null
.
Upvotes: 0
Reputation: 22038
DateTime is a struct/valuetype, so when date = a.dateOne;
is executed, a copy of the datetime is made. When the constructor ends, no reference is held to the instance of A
. So it will be marked to collect.
Upvotes: 0