ReferenceEquals working incorrectly with strings

Why does the ReferenceEquals object method behave differently in this situation?

 string a= "fg"; string b= "fg"; Console.WriteLine(object.ReferenceEquals(a, b)); 

So, in this situation, it gets the result true . In case he compares the values โ€‹โ€‹of my strings, not the links. But when I write something like:

 StringBuilder c = new StringBuilder("fg"); string d = c.ToString(); Console.WriteLine(object.ReferenceEquals(a, d)); 

In this case, it works fine and the result is false , because it compares links to my objects.

+7
source share
4 answers

The first example specifies the compilation time constant "fg" , which is referenced by two variables. Since this is a compile-time constant, two variables refer to the same object. Links are equal.

Read the line feed topic for a more detailed description of this behavior. As a starter, note:

For example, if you assign the same literal string to multiple variables, the runtime gets the same literal string reference from the pool and assigns it to each variable.

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

In the second example, only one is a compile-time constant, the other is the result of some operations. a and d do not reference the same object, so you get a false result from ReferenceEquals .

+13
source

In both cases, he behaves correctly.

The reason a and b is the same string object, because the compiler noticed that you specified the same string twice and reused the same string object to initialize both a and b .

This will happen with every line constant in your application.

+2
source

Since you are referring to the same literal ("fg"), both of your lines will actually point to the same thing. Please take a look at this article: http://csharpindepth.com/Articles/General/Strings.aspx (paragraph "Interning").

Regards, Peter

0
source

According to this post, this is due to what is called internment. a and b in your case are two variables pointing to the same instance, so ReferenceEquals returns true.

0
source

All Articles