String Comparison

  • Thread starter Thread starter Randy
  • Start date Start date
R

Randy

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?

Thanks
 
Randy,

The == operator is defined in terms of String.Equals:

http://msdn.microsoft.com/library/d...ml/frlrfsystemstringclassop_equalitytopic.asp

If you just need to test whether two strings are equal or not, it's simpler
and clearer to use == than Compare().

Compare() is to be used when you need to check whether a string is "less
than", "equal" or "greater than" other following certain sort criteria for
characters:

http://msdn.microsoft.com/library/d...us/cpref/html/frlrfsystemstringclasstopic.asp

Regards - Octavio
 
1. if (string1 ==string2 ) will perfrm a case-sensitive test for equality
between two strings.

2. string.Compare(string1,string2) will perform case-insensitive test
between two strings.


Example int AA = string.Compare("man","man") will return 0 which means they
are equal

Whereas int AA =string.compare("man","MAN") will return a negative number
which mean they are different.

Hope this helps
Yonas
 
Yonas Hagos said:
1. if (string1 ==string2 ) will perfrm a case-sensitive test for equality
between two strings.
Yes.

2. string.Compare(string1,string2) will perform case-insensitive test
between two strings.
No!

Example int AA = string.Compare("man","man") will return 0 which means they
are equal

Whereas int AA =string.compare("man","MAN") will return a negative number
which mean they are different.

That goes against what you said - you said that string.Compare performs
a case-*insensitive* test, but "man" and "MAN" differ only in case. If
string.Compare were case-insensitive, it would return 0.
 
Randy said:
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
 
Back
Top