title: Convert any object to a byte[]
body: <p>I am writing a prototype TCP connection and I am having some trouble homogenizing the data to be sent.</p>
  
  <p>At the moment, I am sending nothing but strings, but in the future we want to be able to send any object. </p>
  
  <p>The code is quite simple at the moment, because I thought everything could be cast into a byte array:</p>
  
  <pre><code>void SendData(object headerObject, object bodyObject)
  {
    byte[] header = (byte[])headerObject;  //strings at runtime, 
    byte[] body = (byte[])bodyObject;      //invalid cast exception
  
    // Unable to cast object of type 'System.String' to type 'System.Byte[]'.
    ...
  }
  </code></pre>
  
  <p>This of course is easily enough solved with a </p>
  
  <pre><code>if( state.headerObject is System.String ){...}
  </code></pre>
  
  <p>The problem is, if I do it that way, I need to check for EVERY type of object that can't be cast to a byte[] at runtime.</p>
  
  <p>Since I do not know every object that can't be cast into a byte[] at runtime, this really isn't an option.</p>
  
  <p>How does one convert any object at all into a byte array in C# .NET 4.0?</p>