Viktor Elofsson Viktor Elofsson - 1 year ago 478
C++ Question

C++ union in C#

I'm translating a library written in C++ to C#, and the keyword 'union' exists once. In a struct.

What's the correct way of translating it into C#? And what does it do? It looks something like this;

struct Foo {
float bar;

union {
int killroy;
float fubar;
} as;

Answer Source

You can use explicit field layouts for that:

public struct SampleUnion
    [FieldOffset(0)] public float bar;
    [FieldOffset(4)] public int killroy;
    [FieldOffset(4)] public float fubar;

Untested. The idea is that two variables have the same position in your struct. You can of course only use one of them.

More informations about unions in struct tutorial

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download