Simulating a C Union

Each field in a struct is given enough room to store its data. Consider a struct containing one int and one char. The int is likely to start at an offset of 0, and is guaranteed at least four bytes. So, the char could start at an offset of 4. If, for some reason, the char started at an offset of 2, then you’d change the value of the int if you assigned a value to the char. Sounds like mayhem, doesn’t it? Strangely enough, the C language supports a variation on a struct called a union that does exactly this. You can simulate this in C# using LayoutKind.Explicit and the FieldOffset attribute.

It might be hard to think of a case in which this would be useful. However, consider a situation in which you want to create a vast quantity of different primitive types, but store them in one array. You have to store them all in an object array, and the primitive values are boxed every time they go into the array. This means you’re going to start using a lot of heap memory, and you’ll pay the cost of boxing and unboxing as you go from primitive to object and back again. This example shows how this works with three objects, but if it were thousands or millions of objects, the impact on performance would be noticeable:

using System; public class BoxMe { public static void Main( ) { // Stuff some primitive values into an array. object[ ] a = new object[3]; a[0] = 1073741824; a[1] = 'A'; a[2] = true; // Display each value foreach (object o in a) { Console.WriteLine("Value: {0}", ...

Get C# in a Nutshell, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.