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:
Since the garbage collector is untyped and only distinguishes between object references and plain bits, overlapping references won't confuse it. However, while one object reference can completely overlap another, this is unverifiable, aka unsafe (ECMA-335 standard, page 180, II.10.7 Controlling instance layout). It's easy to construct a program that exploits this unverifiability to crash horrendously:
using System.Runtime.InteropServices;
class Bar
{
public virtual void func() { }
}
[StructLayout(LayoutKind.Explicit)]
struct Overlaid
{
[FieldOffset(0)]
public object foo;
[FieldOffset(0)]
public Bar bar;
}
class Program
{
static void Main(string[] args)
{
var overlaid = new Overlaid();
overlaid.foo = new object();
overlaid.bar.func();
}
}
Here the func call loads a function pointer from one past the last element of object class's virtual table. According to this article following the vtbl there's a handle table. Treating it as a function pointer leads to a System.AccessViolationException.