Overlaying several CLR reference fields with each other in explicit struct?

Posted by thr on Stack Overflow See other posts from Stack Overflow or by thr
Published on 2010-04-24T07:25:15Z Indexed on 2010/04/24 7:33 UTC
Read the original article Hit count: 167

Filed under:
|
|
|

Edit: I'm well aware of that this works very well with value types, my specific question is about using this for reference types.

I've been tinkering around with structs in .NET/C#, and I just found out that you can do this:

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1 {

    class Foo { }
    class Bar { }

    [StructLayout(LayoutKind.Explicit)]
    struct Overlaid {
        [FieldOffset(0)] public object AsObject;
        [FieldOffset(0)] public Foo AsFoo;
        [FieldOffset(0)] public Bar AsBar;
    }

    class Program {
        static void Main(string[] args) {
            var overlaid = new Overlaid();
            overlaid.AsObject = new Bar();
            Console.WriteLine(overlaid.AsBar);

            overlaid.AsObject = new Foo();
            Console.WriteLine(overlaid.AsFoo);
            Console.ReadLine();
        }
    }
}

Basically circumventing having to do dynamic casting during runtime by using a struct that has an explicit field layout and then accessing the object inside as it's correct type.

Now my question is: Can this lead to memory leaks somehow, or any other undefined behavior inside the CLR? Or is this a fully supported convention that is usable without any issues?

I'm aware that this is one of the darker corners of the CLR, and that this technique is only a viable option in very few specific cases.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET