title: C# optimize memory usage: How to free memory claimed by DataTable
body: <p>Currently I'm optimizing memory-usage of an huge batch-program. The most memory is used by different DataTables. For examle, my DataTable <code>dataTable</code> is using approx 260MB.</p>
  
  <p>Like suggestet in the accepted answer of the thread "<a href="https://stackoverflow.com/questions/424598/what-is-the-memory-overhead-of-storing-data-in-a-net-datatable">What is the memory overhead of storing data in a .NET DataTable?</a>" I'm trying to move relevant data out of the DataTable. This is my code:</p>
  
  <pre><code>GC.Collect(); // force the garbage collector to free memory
  // First stop point - Total process memory (taskmanager) = 900 MB
  List&lt;ExpandoObject&gt; expandoList = new List&lt;ExpandoObject&gt;();
  foreach (DataRow dataRow in dataTable.Rows)
  {
      dynamic expandoItem = new ExpandoObject();
      expandoItem.FieldName = dataRow["FieldName"].ToString();
      expandoList.Add(expandoItem);
  }
  // Second stop point - Total process memory (taskmanager) = 1055 MB
  dataTable.Clear();
  dataTable.Dispose();
  dataTable = null;
  GC.Collect(); // force the garbage collector to free memory
  // Third stop point - Total process memory (taskmanager) = 1081 MB (wtf? even more!)
  </code></pre>
  
  <p>I'm using Clear, Dispose and setting to null because it is suggested in following thread: <a href="https://stackoverflow.com/questions/18869079/datatable-dispose-will-make-it-remove-from-memory">Datatable.Dispose() will make it remove from memory?</a></p>
  
  <p>See the stop points comments to see memory usage at that points. I also tried it with <code>using (DataTable dataTable = ...)</code> but the results were the same.</p>
  
  <p>What am I doing wrong? 
  And maybe is there a better way to minify data from DataTable?</p>