Last active
August 29, 2015 14:07
-
-
Save jbrestan/8b4538be7f9c52189cef to your computer and use it in GitHub Desktop.
Breaking the C# type safety without "unsafe", with explicit struct layout.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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