C# Loop Scope and Memory Issue
<p>Let's say I have the following code...</p>

<pre><code>StringBuilder sb = new StringBuilder();
for (int i = 0; i &amp;lt; 10000; i++)
{
  MyCustomClass myObj = new MyCustomClass();
  sb.Append(myObj.RenderShortString());
}
Console.Write(sb.ToString());
</code></pre>

<p>And assume that MyCustomClass is a very large object. For example, let's say it creates and holds an internal member containing a 1MB string. The RenderShortString() method simply renders a string about 100 characters in length.</p>

<p>Notice this loops 10000 times.</p>

<p>I have something basically like this which is causing System.OutOfMemory exceptions inside the loop.</p>

<p>My question is related to when the memory space allocated for each instance of myObj is cleaned up by the Garbage collector. I don't think I am having an issue with the StringBuilder, but I may be wrong. I get the feeling that the instances of myObj are getting allocated in memory, but not available for cleanup until after the loop is exited. Is this correct? If so, how can I tell the application that as soon as I get my rendered string, I am done with that instance?</p>

<p>Thanks,</p>

<p>Kevin</p>
