Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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}", ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard

Publisher Resources

ISBN: 0596005261Catalog PageErrata