-
-
Save SriramSakthivel/e73fcacf77f910bf3d43 to your computer and use it in GitHub Desktop.
Code snippet for the blog post https://sriramsakthivel.wordpress.com/2014/12/27/breaking-the-clr-type-safety/
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
[StructLayout(LayoutKind.Explicit)] | |
public struct Union | |
{ | |
[FieldOffset(0)] | |
public StringBuilder Builder; | |
[FieldOffset(0)] | |
public string Text; | |
} | |
internal class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
Union union = new Union | |
{ | |
Builder = new StringBuilder() | |
}; | |
//text is not a string, it is StringBuilder. What the heck?? | |
string text = union.Text; | |
//Prints some number, when I run it happens to be 25306168 | |
Console.WriteLine(text.Length); | |
//GetType() returns System.Text.StringBuilder correctly because .net | |
//stores metadata about object in itself. | |
Console.WriteLine(text.GetType()); | |
Console.ReadLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment