String comparison: why we have different results for the cases below

Why do we have a different conclusion for the following cases:

object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;
Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true
Console.WriteLine(obj == str2); // false !?
+4
source share
2 answers

The answer to this is pretty simple:

When comparing objectwith string, a reference comparison is used, which will be true only if both objects have the same link.

When comparing strings, string comparison is used, which will be true if the contents of the string are the same regardless of whether they are the same link.

In the third comparison, you use a comparison objectin which you are comparing two lines with the same content but with different links, so it returns false.

, , interned , .

:

object obj = "Int32";            // As a compile-time constant string, this will be interned.
string str1 = "Int32";           // This is also interned, so has the same reference as obj
string str2 = typeof(int).Name;  // Same contents as str1, but a different reference 
                                 // (created at runtime, so it wasn't interned)
Console.WriteLine(obj == str1);  // Reference comparison: true because the references are the same
Console.WriteLine(str1 == str2); // String comparison: true because the string contents are the same.
Console.WriteLine(obj == str2);  // Reference comparison: false because the references different.

:

  • Resharper, , : " ".
  • , str2 :

    string str2 = string.Concat( "Int", "32" );

+7

obj == str2 . obj == str1 .

?

string .NET - . . , , , .

string, , string. string, . , .

obj == str1 , . , .NET . ( , .) interning, .

, , .NET ?

, . string, .NET all , , , . .

,.NET . , , .

object obj = "Int32";
string str1 = typeof(int).Name;
string str2 = typeof(int).Name;
Console.WriteLine(obj == str1); // false
Console.WriteLine(str1 == str2); // true
Console.WriteLine(obj == str2); // false !?

str1 == str2 - true, , obj == str1 , .

+1

All Articles