How to use Union in C#

Published on Thursday, March 10, 2011
c

There is no Union in C#, however, if you want to use convert Union from C++, do like the following:

C++:

struct Foo { float AA;
union {
    int BB;
    float CC;
} as;

}

**C#:**
[StructLayout(LayoutKind.Explicit)] public struct SampleUnion { [FieldOffset(0)] public float AA; [FieldOffset(4)] public int BB; [FieldOffset(4)] public float CC; }