December 2007
Intermediate to advanced
896 pages
19h 57m
English
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.
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 structure 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;
[FieldOffsetAttribute(0)]
public decimal Num7;
}The next structure is similar to the SignedNumber structure, except that it can contain a String type in addition to the signed numeric value:
[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)] ...Read now
Unlock full access