title: How can I simulate a C++ union in C#?
body: <p>I have a small question about structures with the <code>LayoutKind.Explicit</code> attribute set. I declared the <code>struct</code> as you can see, with a <code>fieldTotal</code> with 64 bits, being <code>fieldFirst</code> the first 32 bytes and <code>fieldSecond</code> the last 32 bytes. After setting both <code>fieldfirst</code> and <code>fieldSecond</code> to <code>Int32.MaxValue</code>, I'd expect <code>fieldTotal</code> to be <code>Int64.MaxValue</code>, which actually doesn't happen. Why is this? I know C# does not really support C++ unions, maybe it will only read the values well when interoping, but when we try to set the values ourselves it simply won't handle it really well? </p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit)]
  struct STRUCT {
      [FieldOffset(0)]
      public Int64 fieldTotal;
  
      [FieldOffset(0)]
      public Int32 fieldFirst;
  
      [FieldOffset(32)]
      public Int32 fieldSecond;
  }
  
          STRUCT str = new STRUCT();
          str.fieldFirst = Int32.MaxValue;
          str.fieldSecond = Int32.MaxValue;
          Console.WriteLine(str.fieldTotal); // &lt;----- I'd expect both these values
          Console.WriteLine(Int64.MaxValue); // &lt;----- to be the same.
          Console.ReadKey();
  </code></pre>