Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why in this situation ReferenceEquals method of object behaves differently?

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

So in this situation it's get a result true. In case, it compares values of my strings and not references. 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 result is false, because it compares references of my objects.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
249 views
Welcome To Ask or Share your Answers For Others

1 Answer

The first example has a compile time constant "fg" that is referenced by two variables. Since this is a compile time constant, the two variables reference the one object. The references are equal.

Read into the topic of string interning for more on this behavior. As a starter, consider:

For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern 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 a result of some operations. a and d do not reference the same object, so you get the false result from ReferenceEquals.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...