Tuesday, February 19, 2008

Creating Unions in C#

Here is a Small trick to create a C/C++ like union in C#.

          You have to use the StructLayout attribute applied to the class. the StructLayout attribute needs to be passed the parameter LayoutKind.Explicit. This makes it so you can declare the exact offset in the number of Bytes each field will have. Naturally you will need to use another attribute for each of the fields to specify this offset; the name of this attribute is FieldOffset. Both of these Attributes are in the System.Runtime.InteropServices namespace.



Here is an example where 2 32bit integers will share the same memory address as a 64bit integer.


using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
public
struct PairID
{
[FieldOffset(0)]
public
long Id;
[FieldOffset(0)]
public
int LowId;
[FieldOffset(sizeof(int))]
public
int HighId;
}