title: Why does LayoutKind.Sequential work differently if a struct contains a DateTime field?
body: <p>Why does LayoutKind.Sequential work differently if a struct contains a DateTime field?</p>
  
  <p>Consider the following code (a console app which must be compiled with "unsafe" enabled):</p>
  
  <pre><code>using System;
  using System.Runtime.InteropServices;
  
  namespace ConsoleApplication3
  {
      static class Program
      {
          static void Main()
          {
              Inner test = new Inner();
  
              unsafe
              {
                  Console.WriteLine("Address of struct   = " + ((int)&amp;test).ToString("X"));
                  Console.WriteLine("Address of First    = " + ((int)&amp;test.First).ToString("X"));
                  Console.WriteLine("Address of NotFirst = " + ((int)&amp;test.NotFirst).ToString("X"));
              }
          }
      }
  
      [StructLayout(LayoutKind.Sequential)]
      public struct Inner
      {
          public byte First;
          public double NotFirst;
          public DateTime WTF;
      }
  }
  </code></pre>
  
  <p>Now if I run the code above, I get output similar to the following:</p>
  
  <p>Address of struct   = 40F2CC<br>
  Address of First    = 40F2D4<br>
  Address of NotFirst = 40F2CC  </p>
  
  <p>Note that the address of First is NOT the same as the address of the struct; however, the address of NotFirst <strong>is</strong> the same as the address of the struct.</p>
  
  <p>Now comment out the "DateTime WTF" field in the struct, and run it again.
  This time, I get output similar to this:</p>
  
  <p>Address of struct   = 15F2E0<br>
  Address of First    = 15F2E0<br>
  Address of NotFirst = 15F2E8  </p>
  
  <p>Now "First" <strong>does</strong> have the same address as the struct.</p>
  
  <p>I find this behaviour surprising given the use of LayoutKind.Sequential. Can anyone provide an explanation? Does this behaviour have any ramifications when doing interop with C/C++ structs that use the Com DATETIME type?</p>
  
  <p>[EDIT] NOTE: I have verified that when you use Marshal.StructureToPtr() to marshal the struct, the data <strong>is</strong> marshalled in the correct order, with the "First" field being first. This seems to suggest that it will work fine with interop. The mystery is why the internal layout changes - but of course, the internal layout is never specified, so the compiler can do what it likes.</p>
  
  <p>[EDIT2] Removed "unsafe" from struct declaration (it was leftover from some testing I was doing).</p>
  
  <p>[EDIT3] The original source for this question was from the MSDN C# forums:</p>
  
  <p><a href="http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/fb84bf1d-d9b3-4e91-823e-988257504b30" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/fb84bf1d-d9b3-4e91-823e-988257504b30</a></p>