title: I'd like to use union as C# with byte array
body: <p>I had idea about message parsing in serial communication, there are many kind of packets which have different form. but they're all sent by byte array.</p>
  
  <p>so I thought using union to parse each message.
  but it's not working well. 
  following code is the sample code which I'm In Error</p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit, Size=12)]
  public struct UnionPacket
  {
      [MarshalAs(UnmanagedType.ByValArray, SizeConst=12)]
      public byte[] data;
  
      [FieldOffset(0)]
      public float Time;
      [FieldOffset(4)]
      public Int16 CoordX;
      [FieldOffset(6)]
      public Int16 CoordY;
      [FieldOffset(8)]
      public byte Red;
      [FieldOffset(9)]
      public byte Green;
      [FieldOffset(10)]
      public byte Blue;
      [FieldOffset(11)]
      public byte Alpha;
  }
  </code></pre>
  
  <p>if this were possible, it would be very happy, but it isn't. This code occurs TypeLoadException "... because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field."</p>
  
  <p>So I changed some code like this</p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit, Size= 12)]
  public struct UnionPacket
  {
      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
      [FieldOffset(0)]
      public byte[] data;
  
      //[FieldOffset(0)]
      //public float Time;
      [FieldOffset(4)]
      public Int16 CoordX;
      [FieldOffset(6)]
      public Int16 CoordY;
      [FieldOffset(8)]
      public byte Red;
      [FieldOffset(9)]
      public byte Green;
      [FieldOffset(10)]
      public byte Blue;
      [FieldOffset(11)]
      public byte Alpha;
  }
  </code></pre>
  
  <p>for test, i just disabled Time field which offset is 0, and this didn't occur Exception. but, if i change other fields, it doesn't change byte array. i think that byte array's real memory location is allocated in other heap, so it cannot be done.</p>
  
  <p>Is there any way to solve this problem in C#? only C++ or C can solve this?
  and if i use this with inheritance, is it possible?</p>
  
  <p>P.S. Sorry about my poor english</p>