Tuesday, September 25, 2007

Hello Eartlings!

For my first post I would like to clear the air about System.String objects. Since the dawn of time humans have all been trying to figure out if two identical strings actually points to the same space in memory. And I might just have the answer!

Last week a colleague of mine rejected the possibility of two identical string objects would share the same space in memory. So I thought about it and wrote a little test.


using System;

 

namespace StringReferenceTest

{

  public class Program

  {

    static void Main(string[] args)

    {

      String string1 = "Hello World";

      String string2 = "Hello World";

 

      Console.WriteLine(String.ReferenceEquals(string1, string2));

      Console.ReadLine();

    }

  }

}


and the result

String reference test result #1

As you can see this little quick test told me that the two string objects had the same reference. But this didn't really satisfy me, why not go a little further and get the two objects memory address?

using System;

 

namespace StringReferenceTest

{

  public class Program

  {

    static unsafe void Main(string[] args)

    {

      String string1 = "Hello World";

      String string2 = "Hello World";

 

      Console.WriteLine(String.ReferenceEquals(string1, string2));

 

      fixed (char* p = string1)

      Console.WriteLine((IntPtr)p);

 

      fixed (char* p = string2)

      Console.WriteLine((IntPtr)p);

 

      Console.ReadLine();

    }

  }

}


and the result

String reference test result #2

Again the test told me that the two string objects were referencing the same address. Notice for this last test to work you need to specify the "unsafe" statement in the method signature and set the project's build settings to allow unsafe code.

So now you know :)


Download
To download the full project click here.


0 comments: