title: C# StructLayout.Explicit Question
body: <p>I'm trying to understand why the second example below works with no issues, but the first example gives me the exception below. It seems to me that both examples should give an exception based on the description. Can anyone enlighten me?</p>
  
  <blockquote>
    <p>Unhandled Exception:
    System.TypeLoadException: Could not
    load type 'StructTest.OuterType' from
    assembly 'StructTest, Version=1.0.0.0,
    Culture=neutral,  PublicKeyToken=null'
    because it contains an object field at
    offset 0 that is incorrectly aligned
    or overlapped by a non-object field.<br>
    at StructTest.Program.Main(String[]
    args) Press any key to continue . . .</p>
  </blockquote>
  
  <p><strong>Example 1</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Runtime.InteropServices;
  using System.Text;
  
  namespace StructTest
  {
      [StructLayout(LayoutKind.Sequential, Pack = 1)]
      struct InnerType
      {
          [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
          char[] buffer;
      }
  
      [StructLayout(LayoutKind.Explicit)]
      struct OuterType
      {
          [FieldOffset(0)]
          int someValue;
  
          [FieldOffset(0)]
          InnerType someOtherValue;
      }
  
      class Program
      {
          static void Main(string[] args)
          {
              OuterType t = new OuterType();
              System.Console.WriteLine(t);
          }
      }
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Example 2</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Runtime.InteropServices;
  using System.Text;
  
  namespace StructTest
  {
      [StructLayout(LayoutKind.Sequential, Pack = 1)]
      struct InnerType
      {
          [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
          char[] buffer;
      }
  
      [StructLayout(LayoutKind.Explicit)]
      struct OuterType
      {
          [FieldOffset(4)]
          private int someValue;
  
          [FieldOffset(0)]
          InnerType someOtherValue;
  
      }
  
      class Program
      {
          static void Main(string[] args)
          {
              OuterType t = new OuterType();
              System.Console.WriteLine(t);
          }
      }
  }
  </code></pre>