How to compare two objects with string values?

I use this code And get the true result:

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

But when I try to downgrade: object text2 = "test".ToLower(); Am I getting a false result?

  object text1 = "test".ToLower(); object text2 = "test".ToLower(); Console.WriteLine("text1 == text2 : " + (text1 == text2)); //return:false 
+7
source share
2 answers

In the first case, you compare two strings using referential equality, but two strings: interned strings .

In the second case, when you call ToLower() on a string, it creates a new string, so you compare two new string instances that are not the same instance when compared using reference equality.

If you compare the String.Equals method and do not use Object.Equals , you will find that it will return true, since String.Equals will compare based on the value contained in the string, and not the actual object references.

+14
source

I would suggest that this is because you are testing for equality of objects, not for equality of strings.

That is, in the first example, the compiler made the repository text1 and text2 the actual same object, since the contents are the same. In the second example, new objects are returned by calling ToLower () and, therefore, are no longer the same object.

If you change the declared storage type from an object to a string, you will see the desired behavior.

+3
source

All Articles