title: C# parse bytes to struct sequential
body: <p>I try parse a byte array to struct but it doesnt work with Sequential. The values are wrong in the Sequential struct but it work correct with Explicit struct? I need sequential the byte array have no fix length. The DwLength field is the size of Data field.</p>
  
  <p><strong>Values</strong></p>
  
  <ul>
  <li>MessageType 128 (Sequential 128)</li>
  <li>DwLength 20 (Sequential 33554432)</li>
  <li>Slot 0 (Sequential 0)</li>
  <li>Seq 0 (Sequential 0)</li>
  <li>Status 2 (Sequential 59)</li>
  <li>Error 0 (Sequential 143)</li>
  <li>ChainParameter 0 (Sequential 128)</li>
  </ul>
  
  <p><strong>Test Code</strong></p>
  
  <pre><code>var bytes = new byte[] { 0x80, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x3B, 0x8F, 0x80, 0x01, 0x80, 0x4F, 0x0C, 0xA0, 0x00, 0x00, 0x03, 0x06, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x68 };
  
  var result1 = GetStruct&lt;RdrToPcDataBlock1&gt;(bytes);
  var result2 = GetStruct&lt;RdrToPcDataBlock2&gt;(bytes);
  </code></pre>
  
  <p><strong>struct RdrToPcDataBlock Sequential</strong></p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential)]
  public struct RdrToPcDataBlock1
  {
      public byte MessageType;
      public int DwLength;
      public byte Slot;
      public byte Seq;
      public byte Status;
      public byte Error;
      public byte ChainParameter;
      [MarshalAs(UnmanagedType.ByValArray)]
      public byte[] Data;
  }
  </code></pre>
  
  <p><strong>struct RdrToPcDataBlock Explicit</strong></p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit)]
  public struct RdrToPcDataBlock2
  {
      [FieldOffset(0)]
      public byte MessageType;
      [FieldOffset(1)]
      public int DwLength;
      [FieldOffset(5)]
      public byte Slot;
      [FieldOffset(6)]
      public byte Seq;
      [FieldOffset(7)]
      public byte Status;
      [FieldOffset(8)]
      public byte Error;
      [FieldOffset(9)]
      public byte ChainParameter;
      [FieldOffset(10)]
      public byte Data;
  }
  </code></pre>
  
  <p><strong>GetStruct</strong></p>
  
  <pre><code>public T GetStruct&lt;T&gt;(byte[] bytes)
  {
      try
      {
          var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
          var item = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
          handle.Free();
          return item;
      }
      catch
      {
          return default(T);
      }
  }
  </code></pre>