Skip to main content
Source Link
ZeroBugBounce
  • 3.7k
  • 3
  • 34
  • 40

Unions (the C++ shared memory kind) in pure, safe C#

Without resorting to unsafe mode and pointers, you can have class members share memory space in a class/struct. Given the following class:

[StructLayout(LayoutKind.Explicit)] public class A { [FieldOffset(0)] public byte One; [FieldOffset(1)] public byte Two; [FieldOffset(2)] public byte Three; [FieldOffset(3)] public byte Four; [FieldOffset(0)] public int Int32; } 

You can modify the values of the byte fields by manipulating the Int32 field and vice-versa. For example, this program:

 static void Main(string[] args) { A a = new A { Int32 = int.MaxValue }; Console.WriteLine(a.Int32); Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", a.One, a.Two, a.Three, a.Four); a.Four = 0; a.Three = 0; Console.WriteLine(a.Int32); } 

Outputs this:

2147483647 FF FF FF 7F 65535 

just add using System.Runtime.InteropServices;

Post Made Community Wiki by CommunityBot