Unions
If your data needs to contain a lot of different fields for different cases, consider using a union.
using System.Runtime.InteropServices;
public enum TargetType : byte
{
Point,
Region,
Entity,
}
[StructLayout (LayoutKind.Explicit, Pack = 1)]
public struct Target
{
[FieldOffset(0)] public readonly TargetType TargetType;
[FieldOffset(1)] public readonly Vector3 Point;
[FieldOffset(1)] public readonly Region Region;
[FieldOffset(1)] public readonly Entity Entity;
}
Here, Point
, Region
and Entity
occupy the same memory space. The [FieldOffset]
attribute takes a number of bytes as argument. since our enum TargetType
has a size of 1 byte, the 3 fields are offset by 1 byte in memory.
To learn more about unions, see http://jacksondunstan.com/articles/3325