Is FieldOffset
aliasing safe for reference types?
#96321
-
Suppose I am making a runtime for a language, and I want to use a discriminated union for storage of value types: public readonly struct Value : IObject
{
ulong _meta; // discriminant and more
IObject? _obj; // null if a value type
string? _string; // null if not a string
bool _boolean; // false if not a boolean
long _integer; // zero if not an integer
double _float; // zero if not a float
// ...
} The problem is: that's a lot of wasted space for unused fields. I figure I could use [StructLayout(LayoutKind.Explicit)]
public readonly struct Value : IObject
{
[FieldOffset(0)]
ulong _meta;
[FieldOffset(8)]
IObject? _obj;
[FieldOffset(8)]
string? _string;
[FieldOffset(8)]
bool _boolean;
[FieldOffset(8)]
long _integer;
[FieldOffset(8)]
double _float;
// ...
} However, now I've aliased value types on top of reference types. Even though I'd be able to tell when the bytes at offset eight are and aren't pointers (based on the metadata), the runtime/GC wouldn't. If Is this safe in C#? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It is not safe, and your example will result in a |
Beta Was this translation helpful? Give feedback.
It is not safe, and your example will result in a
TypeLoadException
when you try to use theValue
type.