Skip to content

Instantly share code, notes, and snippets.

@SriramSakthivel
Created January 20, 2015 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SriramSakthivel/e73fcacf77f910bf3d43 to your computer and use it in GitHub Desktop.
Save SriramSakthivel/e73fcacf77f910bf3d43 to your computer and use it in GitHub Desktop.
[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