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.

public struct MyUnion
	public byte byte1;
	public byte byte2;
	public byte byte3;
	public byte byte4;

	public int number;

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

                     u.byte1, u.byte2, u.byte3, u.byte4);