
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Creating Union-Type Structures
|
89
[StructLayoutAttribute(LayoutKind.Explicit)]
struct SignedNumberWithText
{
[FieldOffsetAttribute(0)]
public sbyte Num1;
[FieldOffsetAttribute(0)]
public short Num2;
[FieldOffsetAttribute(0)]
public int Num3;
[FieldOffsetAttribute(0)]
public long Num4;
[FieldOffsetAttribute(0)]
public float Num5;
[FieldOffsetAttribute(0)]
public double Num6;
[FieldOffsetAttribute(0)]
public decimal Num7;
[FieldOffsetAttribute(16)]
public string Text1;
}
Discussion
Unions are structures usually found in C++ code; however, there is a way to dupli-
cate that type of structure using a C# structure data type. A union is a structure that
accepts more than one type at a specific location in memory for that structure. For
example, the
SignedNumber structure is a union-type structure built using a C# struc-
ture. This structure accepts any type of signed numeric type (
sbyte, int, long, etc.),
but it accepts this numeric type at only one location, or offset, within the structure.
Since StructLayoutAttribute can be applied to both structures and
classes, a class can also be used when creating a union data type.
Notice the FieldOffsetAttribute has the value zero passed to its constructor. This
denotes that this field will be at the zeroth offset (this is a byte offset) within this ...