"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:uB*************@TK2MSFTNGP15.phx.gbl...
Hi
I am looking at some code which in many places performs string comparison
using == instead of Equals.
To add to the other posts, here's some additional info from
what I've seen.
Example code :
private void button10_Click(object sender, System.EventArgs e)
{
string s1 = "hello"; // XXX
string s2 = string.Copy(s1);
if (s1 == s2)
MessageBox.Show("Test 1 : was equal");
else
MessageBox.Show("Test 1 : not equal");
object s1obj = s1;
if (s1obj == "hello") // YYY
MessageBox.Show("Test 2 : was equal");
else
MessageBox.Show("Test 2 : not equal");
if (s1obj == s2) // ZZZ
MessageBox.Show("Test 3 : was equal");
else
MessageBox.Show("Test 3 : not equal");
}
When run, this code displays :
"Test 1 : was equal"
"Test 2 : was equal"
"Test 3 : not equal"
The string class overloads the following "==" operator :
public static bool operator ==(string a, string b)
, so that when you use the "==" operator on two strings, the actual contents
of
the string are compared, and not their references. That is why test 1
passes.
In case of test 2, the overloaded "==" operator defined in the string class
is not invoked, because the s1obj variable is of type "object".
This results in a reference comparison. This is also what happens in test 3.
However, the results of test 2 and test 3 are different.
This is because in test 2, we got lucky, since the lteral constant : "hello"
on line marked "XXX" is the same (i.e. the same reference) as the literal
constant "hello" marked on line YYY. (I guess this is probably due to
dotnet realizing that the strings hold the same contents, so just make
them point to the one copy). (You could confirm this by evaluating
something like : object.ReferenceEquals(s1obj, "hello"), which
returns true.)
Even though test 2 worked, it is not really a good idea to use code
like this. (As shown by test 3).
The C# compiler even gives you a warning about lines YYY and ZZZ :
==
form1.cs(334,8): warning CS0252: Possible unintended reference
comparison; to get a value comparison, cast the left
hand side to type 'string'
==