title: How to convert an object to a byte array in C#
body: <p>I have a collection of objects that I need to write to a binary file.  </p>
  
  <p>I need the bytes in the file to be compact, so I can't use <code>BinaryFormatter</code>.  <code>BinaryFormatter</code> throws in all sorts of info for deserialization needs.</p>
  
  <p>If I try </p>
  
  <pre><code>byte[] myBytes = (byte[]) myObject 
  </code></pre>
  
  <p>I get a runtime exception.</p>
  
  <p>I need this to be fast so I'd rather not be copying arrays of bytes around.  I'd just like the cast <code>byte[] myBytes = (byte[]) myObject</code> to work!</p>
  
  <p> OK just to be clear, I cannot have <em>any</em> metadata in the output file.  Just the object bytes.  Packed object-to-object.  Based on answers received, it looks like I'll be writing low-level <code>Buffer.BlockCopy</code> code.  Perhaps using unsafe code.  </p>