I like the C# language very much. I'm just playing around, and would never use the code below in production code. Obviously the compiler is fooled by the layout of the struct. But how come, that the string on the Super class can still be written and read in run-time? I would have expected some memory access violation. Inspecting the type during run time, it says it is of type Base, see the NoProblem()
function execution. No Super class has been instantiated.
How is it able to function like this?
using System;
using System.Runtime.InteropServices;
namespace Fiddle
{
class Program
{
static void Main(string[] args)
{
var b = new Base
{
IntOnBase = 1
};
var overlay = new Overlay();
overlay.Base = b;
var super = overlay.Super;
var intValue = super.IntOnBase;
super.StringOnSuper = "my test string";
var stringValue = super.StringOnSuper;
super.NoProblem();
Expressions.Fiddle();
}
}
[StructLayout(LayoutKind.Explicit)]
public struct Overlay
{
[FieldOffset(0)]
public Super Super;
[FieldOffset(0)]
public Base Base;
}
public class Super : Base
{
public string StringOnSuper { get; set; }
public void NoProblem()
{
Console.WriteLine("You know, I am really a " + this.GetType().Name + " kind of class.");
}
}
public class Base
{
public int IntOnBase { get; set; }
}
}
super.StringOnSuper
before you assign it? I'd expect it to be uninitialized, since the constructor ofBase
does not know it. – GodfreyFieldOffset
should be deemedunsafe
. – Worth