Edit: I\'m well aware of that this works very well with value types, my specific question is about using this for reference types.
Edit2:
I can't see how the explicit-layout version can be verifiable without the runtime injecting extra checks anyway, since it allows you to see a non-null reference to something that isn't of the declared type.
This would be safer:
struct Overlaid { // could also be a class for reference-type semantics
private object asObject;
public object AsObject {get {return asObject;} set {asObject = value;} }
public Foo AsFoo { get {return asObject as Foo;} set {asObject = value;} }
public Bar AsBar { get {return asObject as Bar;} set {asObject = value;} }
}
No risk of torn references etc, and still only a single field. It doesn't involve any risky code, etc. In particular, it doesn't risk something silly like:
[FieldOffset(0)]
public object AsObject;
[FieldOffset(0)]
public Foo AsFoo;
[FieldOffset(1)]
public Bar AsBar; // kaboom!!!!
Another issue is that you can only support a single field this way unless you can guarantee the CPU mode; offset 0 is easy, but it gets trickier if you need multiple fields and need to support x86 and x64.