Skip to content

Instantly share code, notes, and snippets.

@jbrestan
Last active August 29, 2015 14:07
Show Gist options
  • Save jbrestan/8b4538be7f9c52189cef to your computer and use it in GitHub Desktop.
Save jbrestan/8b4538be7f9c52189cef to your computer and use it in GitHub Desktop.
Breaking the C# type safety without "unsafe", with explicit struct layout.
void Main()
{
var u = new Union
{
Foo = null,
Bar = new Bar()
};
u.Foo.S = "ohai!";
u.Bar.I.Dump();
u.Foo.S.Dump();
}
[StructLayout(LayoutKind.Explicit)]
struct Union
{
[FieldOffset(0)]
public Foo Foo;
[FieldOffset(0)]
public Bar Bar;
}
class Foo
{
public string S { get;set; }
}
class Bar
{
public int I { get;set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment