How can I implement C/C++ "union" in C#?
C# doesn't natively support the C/C++ notion of unions. However, you can use the StructLayout(LayoutKind.Explicit) and FieldOffset attributes to create equivalent functionality. Try the given code below:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct Data {
[FieldOffset(0)]
public byte Byte1;
[FieldOffset(1)]
public byte Byte2;
[FieldOffset(2)]
public byte Byte3;
[FieldOffset(3)]
public byte Byte4;
[FieldOffset(4)]
public byte Byte5;
[FieldOffset(5)]
public byte Byte6;
[FieldOffset(6)]
public byte Byte7;
[FieldOffset(7)]
public byte Byte8;
[FieldOffset(0)]
public int Int1;
[FieldOffset(4)]
public int Int2;
}
One thing to be careful of is the endian-ness of the machine if you plan to run it on non-x86 platforms that may have differing endianness.
See http://en.wikipedia.org/wiki/Endianness for an explanation.