C# Tips

C# Tip Article

C# Union

In C/C++, union is a user-defined type in which all members share the same memory, but uses only one of its members at a time. For example, below is C/C++ union that can be used with 4 chars or one int.

 
union MyUnion 
{
	char c[4];
	int i;
};

C# does not natively support C/C++ style union. But we can use Explicit StructLayout to build a similar union style structure.


To make union in C#, we need to do:
1) specify StructLayout attribute with LayoutKind.Explicit parameter.
2) specify FieldOffset attribute with offset index.

Here is an example of C# union.

    
[StructLayout(LayoutKind.Explicit)]
public struct MyUnion
{
	[FieldOffset(0)]
	public byte byte1;
	[FieldOffset(1)]
	public byte byte2;
	[FieldOffset(2)]
	public byte byte3;
	[FieldOffset(3)]
	public byte byte4;

	[FieldOffset(0)]
	public int number;
}

class Program
{
	static void Main(string[] args)
	{
		MyUnion u = new MyUnion();
		u.number = 365;

		Console.WriteLine("{0:X},{1:X},{2:X},{3:X}", 
                     u.byte1, u.byte2, u.byte3, u.byte4);            
	}
}