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:
If you align the type in an unsafe way, the runtime will throw a TypeLoadException
on load even when compiling with /unsafe
. So I think you are safe.
I'm guessing--since you can use StructLayout
and compile your code without /unsafe
flags-- that this is a feature of the CLR. You need the StructLayout attribute simply because C# has no direct means of declaring types this way.
Take a look at this page which details some of the way C# structs translates into IL, you'll notice that there are many memory layouts support built-in to the IL/CLR itself.