7

I use this code And get true result:

 object text1 = "test";
 object text2 = "test";
 Console.WriteLine("text1 == text2 : " + (text1 == text2));
 //return:true

But when i try to lower:object text2 = "test".ToLower();i get false result?

   object text1 = "test".ToLower();
   object text2 = "test".ToLower();
   Console.WriteLine("text1 == text2 : " + (text1 == text2));
   //return:false
4

2 回答 2

13

In the first case, you're comparing two strings using reference equality, but the two strings are interned strings.

In the second case, when you call ToLower() on the string, it makes a new string, so you're comparing two new string instances, which are not the same instance when compared using reference equality.

If you do the comparison with the String.Equals method, and don't use Object.Equals, you'll find that it will return true, since String.Equals will compare based off the value contained within the string, not the actual object references.

于 2013-05-20T16:15:05.113 回答
2

I would presume that this is because you are testing for object equality, not string equality.

That is to say in the first example the compiler has made the storage of text1 and text2 the actual same object since the contents are the same. In the second example new objects are returned by the ToLower() call and hence aren't the same object any more.

If you change the declared storage type from object to string you should see the desired behaviour.

于 2013-05-20T16:15:56.583 回答