title: Byte for byte serialization of a struct in C#
body: <p>I'm looking for language support of serialization in C#. I could derive from ISerializable and implement the serialization by copying member values in a byte buffer. However, I would prefer a more automatic way like one could do in C/C++.</p>
  
  <p>Consider the following code :</p>
  
  <pre><code>using System;
  using System.Text;
  using System.Runtime.Serialization;
  using System.Runtime.Serialization.Formatters.Binary;
  using System.IO;
  
  namespace XBeeHelper
  {
      class XBee
      {
          [Serializable()]
          public struct Frame&lt;FrameType&gt; where FrameType : struct
          {
              public Byte StartDelimiter;
              public UInt16 Lenght;
              public Byte APIIdentifier;
              public FrameType FrameData;
              public Byte Checksum;
          }
  
          [Serializable()]
          public struct ModemStatus
          {
              public Byte Status;
          }
  
          public Byte[] TestSerialization()
          {
              Frame&lt;ModemStatus&gt; frame = new Frame&lt;ModemStatus&gt;();
              frame.StartDelimiter = 1;
              frame.Lenght = 2;
              frame.APIIdentifier = 3;
              frame.FrameData.Status = 4;
              frame.Checksum = 5;
  
              BinaryFormatter formatter = new BinaryFormatter();
              MemoryStream stream = new MemoryStream();
              formatter.Serialize(stream, frame);
              Byte[] buffer = stream.ToArray();
              return buffer;
          }
      }
  }
  </code></pre>
  
  <p>I have a generic Frame struct acting as a wrapper for many types of payload, for serial transmission. ModemStatus is an example of such payload.</p>
  
  <p>However, running TestSerialization() returns a buffer <strong>382</strong> bytes long (without the expected content)! It should have contained 6 bytes. Is it possible to serialize this data correctly without manual serializing?</p>