The immutable string

Mark Michaelis posted a challenge: modify a string such that the following would print “Smile”:

class Program
{
  static void Main()
  {
      string text;
      // …
      // Place code here
      // …
      text = “S5280ft”;
      System.Console.WriteLine(text);
  }
}

His solution?

class Program
{
  static void Main()
  {
      string text;
      unsafe {
          fixed (char* pText = text) {
              pText[1] = ’m’;
              pText[2] = ‘i’;
              pText[3] = ‘l’;
              pText[4] = ‘e’;
          }
      }
      text = “S5280ft”;
      System.Console.WriteLine(text);
  }
}

My answer; note that I believe mine to be cleaner, more elegant, and far far more dangerous, since it never uses any sort of unsafe code:

class Program
{
  static void Main()
  {
      string text;

  <SPAN class=kwrd>string</SPAN> internedText = "S5280ft";
  String.Intern(internedText);
  MethodInfo mi = typeof(<SPAN class=kwrd>string</SPAN>).GetMethod(<SPAN class=str>"InsertInPlace"</SPAN>, 
    BindingFlags.NonPublic | BindingFlags.Instance, null,
    new Type[] { typeof(Int32), typeof(<SPAN class=kwrd>string</SPAN>), typeof(Int32), typeof(Int32), typeof(Int32) }, <SPAN class=kwrd>null</SPAN>);
  mi.Invoke(internedText, new <SPAN class=kwrd>object</SPAN>[] {0, <SPAN class=str>"Smile"</SPAN>, 1, 7, 5});      

  text = <SPAN class=str>"S5280ft"</SPAN>;
  System.Console.WriteLine(text);

} }

The point? Playing with Reflection can be dangerous… oh, and it helps to know that strings are only as immutable as the platform forces them to be. In this case, my little hack would only be possible because under the covers, .NET doesn’t really have immutable strings–it just doesn’t let YOU modify them. :-)

(By the way, same trick is available in Java, using the same approach. Or you could write JNI code to sort of duplicate Mark’s trick, but who’d want to do that? Brrr.)