
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
90
|
Chapter 3: Classes and Structures
Unions can become problematic, since several types are essentially laid on top of one
another. The biggest problem is extracting the correct data type from a union struc-
ture. Consider what happens if you choose to store the
long numeric value long.
MaxValue
in the SignedNumber structure. Later, you might accidentally attempt to
extract a
byte data type value from this same structure. In doing so, you will get back
only the first byte of the long value.
Another problem is starting fields at the correct offset. The
SignedNumberWithText
union overlays numerous signed numeric data types at the zeroth offset. The last
field in this structure is laid out at the 16th byte offset from the beginning of this
structure in memory. If you accidentally overlay the string field
Text1 on top of any
of the other signed numeric data types, you will get an exception at runtime. The
basic rule is that you are allowed to overlay a value type on another value type, but
you cannot overlay a reference type over a value type. If the
Text1 field is marked
with the following attribute:
[FieldOffsetAttribute(14)]
this exception is thrown at runtime (note that the compiler does not catch this
problem):
An unhandled exception of type 'System.TypeLoadException' occurred in
Chapter_Code.exe. ...