mesman00 mesman00 - 1 month ago 19
C# Question

C# Memory Management

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.

Answer

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.

Comments