
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
88
|
Chapter 3: Classes and Structures
• Its fields need to be initialized only to their default values. This value would be
zero for numeric types, false for Boolean types, and null for reference types.
• You do not need to inherit from a base class (other than
ValueType, from which
all structs inherit).
• You do not need polymorphic behavior.
3.1 Creating Union-Type Structures
Problem
You need to create a data type that behaves like a union type in C++. A union type is
useful mainly in interop scenarios in which the unmanaged code accepts and/or
returns a union type; we suggest that you do not use it in other situations.
Solution
Use a structure and mark it with the StructLayout attribute (specifying the LayoutKind.
Explicit
layout kind in the constructor). In addition, mark each field in the struc-
ture with the
FieldOffset attribute. The following structure defines a union in which
a single signed numeric value can be stored:
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Explicit)]
struct SignedNumber
{
[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; ...