Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.ReferenceEquals returns true for matching strings

Tags:

string

c#

mono

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

like image 892
Mert Akcakaya Avatar asked Jul 05 '26 16:07

Mert Akcakaya


2 Answers

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
    }
like image 173
DeveloperGuo Avatar answered Jul 08 '26 08:07

DeveloperGuo


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
like image 23
Sudhakar Tillapudi Avatar answered Jul 08 '26 08:07

Sudhakar Tillapudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!