Skip to content

Instantly share code, notes, and snippets.

@hanswolff
Last active August 29, 2015 14:07
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 hanswolff/f01ac03e590ce580fe45 to your computer and use it in GitHub Desktop.
Save hanswolff/f01ac03e590ce580fe45 to your computer and use it in GitHub Desktop.
Break interned string representation
using System;
using System.Runtime.InteropServices;
class Program
{
[StructLayout(LayoutKind.Explicit)]
struct Union
{
[FieldOffset(0)]
public string A;
[FieldOffset(0)]
public Breaker B;
}
class Breaker
{
public int Length;
public char FirstChar;
}
static void Main(string[] args)
{
var u = new Union();
u.A = "aaaa";
u.B.FirstChar = 'b';
Console.WriteLine("aaaa".StartsWith("a")); // false
}
}
@ploeh
Copy link

ploeh commented Oct 22, 2014

Wow, I don't even understand what that does :$

@hanswolff
Copy link
Author

It's a hack to mutate the interned string literal using a struct with overlapping object references. It's a known glitch in the .NET Framework

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment