title: System.OutOfMemory exception when calling MemoryStream.ToArray() after serializing object with DataContractSerializer
body: <p>I am getting an intermittent "out of memory" exception at this statement:</p>
  
  <pre><code>        return ms.ToArray();
  </code></pre>
  
  <p>In this method:</p>
  
  <pre><code>public static byte[] Serialize(Object inst)
  {
      Type t = inst.GetType();
      DataContractSerializer dcs = new DataContractSerializer(t);
      MemoryStream ms = new MemoryStream();
      dcs.WriteObject(ms, inst);
      return ms.ToArray();
  }
  </code></pre>
  
  <p>How can I prevent it?  Is there a better way to do this?</p>
  
  <p>The length of ms is 182,870,206 bytes (174.4 MB)</p>
  
  <p>I am putting this into a byte array so that I can then run it through compression and store it to disk.  The data is (obviously) a large list of a custom class that I am downloading from a WCF server when my silverlight application starts.  I am serializing it and compressing it so it uses only about 6MB in isolated storage.  The next time the user visits and runs the silverlight application from the web, I check the timestamp, and if good I just open the file from isolated, decompress it, deserialize it, and load my structure.  I am keeping the entire structure in memory because the application is mostly geared around manipulating the contents of this structure.</p>
  
  <p>@configurator is correct.  The size of the array was too big.  I rolled by own serializer, by declaring a byte array of [list record count * byte count per record], then stuffed it directly myself using statements like this to stuff it:</p>
  
  <pre><code>    Buffer.BlockCopy(
             BitConverter.GetBytes(node.myInt),0,destinationArray,offset,sizeof(int)); 
      offset += sizeof(int);
  </code></pre>
  
  <p>and this to get it back:</p>
  
  <pre><code>    newNode.myInt= BitConverter.ToInt32(sourceByteArray,offset); 
      offset += sizeof(int);
  </code></pre>
  
  <p>Then I compressed it and stored it to isolated storage.</p>
  
  <p>My size went from 174MB with the DataContractSerializer to 14MB with mine.
  After compression it went from a 6MB to a 1MB file in isolated storage.</p>
  
  <p>Thanks to Configurator and Filip for their help.</p>