I am trying to understand the technicalities behind why C# does not have unions. I understand that using the attribute mechanism with explicit structure layout does the trick, I am more interested in why this was preferred over vanilla union construct.
Share
Allowing unions would undermine the safety of .NET, especially when it comes to managed objects.
For example (for 32-bit systems):
C# does allow you to shoot yourself in the foot with the unsafe keyword and with certain attributes, but never involving managed types. You might have noticed that FieldOffset doesn’t let you combine random types together. Try it with the above “union”.
Here’s what I get: