3

I am using Mono and encountered an interesting result when comparing references of two strings. The code below demonstrates an example:

using System;

class Program
{
    static void Main()
    {
        String s1 = "asd";
        String s2 = "asd";
        Console.WriteLine("Reference Equals: {0}", Object.ReferenceEquals(s1, s2));

        Console.ReadLine();
    }
}

Yields true.

It is interesting, two strings have same value but obviously they refer to two different instances. What is going on?

mono --version : Mono JIT compiler version 3.2.6 OS X 10.9.2

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42

2 Answers2

4

http://msdn.microsoft.com/en-us/library/system.string.intern.aspx

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

The below shows behavior when strings are not created from a string literal.

    static void Main(string[] args)
    {
        var string1 = new string(new []{'c'});
        var string2 = new string(new []{'c'});
        Console.WriteLine(string1.Equals(string2));                 //true
        Console.WriteLine(Object.ReferenceEquals(string1,string2)); //false
    }
DeveloperGuo
  • 636
  • 5
  • 15
1

It is interesting, two strings have same value but obviously they refer to two different instances

no they dont refer to two different instances, infact there are no two different instances there is only one instance created as you are providing same string literal.

in your program for all similar string constants one and only instance is created and all string reference variables refer the same instance hence when you run the ReferenceEquals() method on of those references, you will get True a they are logically referring same instance.

From : String Interning

The CLR maintains a table called the intern pool that contains a single, unique reference to every literal string that's either declared or created programmatically while your program's running.

if you want to see the expected result try the below snippet. it will create two different instances as they are passed to constructor.

Try This:

String s1 = new String("asd".ToCharArray());
String s2 = new String("asd".ToCharArray());
Console.WriteLine("Reference Equals: {0}",Object.ReferenceEquals(s1, s2));//False
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67