How can I simulate a C++ union in C#?

.net, c#, c++, struct, unions

Solution

The reason is that FieldOffsetAttribute takes a number of bytes as parameter -- not number of bits. This works as expected:

[StructLayout(LayoutKind.Explicit)]
struct STRUCT
{
    [FieldOffset(0)]
    public Int64 fieldTotal;

    [FieldOffset(0)]
    public Int32 fieldFirst;

    [FieldOffset(4)]
    public Int32 fieldSecond;
}

Problem

I have a small question about structures with the `LayoutKind.Explicit` attribute set. I declared the `struct` as you can see, with a `fieldTotal` with 64 bits, being `fieldFirst` the first 32 bytes and `fieldSecond` the last 32 bytes. After setting both `fieldfirst` and `fieldSecond` to `Int32.MaxValue`, I'd expect `fieldTotal` to be `Int64.MaxValue`, 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? ``` [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); // <----- I'd expect both these values Console.WriteLine(Int64.MaxValue); // <----- to be the same. Console.ReadKey(); ```

Original source