"Randy" <te**@temp.com> wrote in message
news:ex**************@TK2MSFTNGP14.phx.gbl...
Hello,
In comparing strings, is it just as well to use...
string1 == string2
or is it better for any reason to use the String.Compare of String.Equals?
Assuming you want a case-sensitive comparison :
string1 == string2 is ok, as long as both sides are strings
(and not objects) at compile time.
eg.
==
string s1 = "abc";
string s2 = s1.ToLower();
if (object.ReferenceEquals(s1, s2))
MessageBox.Show("string references equal");
else
MessageBox.Show("string references not equal"); // A
if (s1 == s2)
MessageBox.Show("(s1 == s2) is true"); // B
else
MessageBox.Show("(s1 == s2) is false");
object o1 = s1;
object o2 = s2;
if (o1 == o2)
MessageBox.Show("(o1 == o2) is true");
else
MessageBox.Show("(o1 == o2) is false"); // C
if (String.Equals(o1, o2))
MessageBox.Show("(String.Equals) is true"); // D
else
MessageBox.Show("(String.Equals) is false");
==
When run, the code above outputs
(at least on my PC) the lines marked at
A, B, C and D.
Watch out for tests like (o1 == o2),
since a reference comparison is performed.
When both sides are objects, IMO, it is
safer to use one of the String.Equals
or object.Equals variants.
HTH,
Stephen