Peter said:
String objects are references to the actual strings. As such, they hold the
address of a string.
If you use == to compare String objects, you are comparing addresses, not
the contents of the strings.
Unless you've created two references to the same string, s1 == s2 will never
be true.
Use the methods defined in the String class.
The help file for the String class states "This operator is implemented
using the Equals method, which means the comparands are tested for a
combination of reference and value equality." What exactly does this
mean? I use (stringa == stringb) all of the time without issue, and the
examples do exactly the same thing.
However, Equals() does not say the same as above. So what exactly is the
difference?
I am writing this because I disagree with your statement "If you use ==
to compare String objects, you are comparing addresses, not the contents
of the strings."
This is clearly untrue both in practice and in the help file, although
it does seem there is some nuance that needs to be understood.
David Logan
From MSDN itself, describing the String class:
Determines whether two specified String objects have the same value.
[Visual Basic]
returnValue = String.op_Equality(a, b)
[C#]
public static bool operator ==(
string a,
string b
);
[C++]
public: static bool op_Equality(
String* a,
String* b
);
[JScript]
returnValue = a == b;
[Visual Basic] In Visual Basic, you can use the operators defined by a
type, but you cannot define your own. You can use the Equals method
instead of the String equality operator.
[JScript] In JScript, you can use the operators defined by a type, but
you cannot define your own.
Arguments [Visual Basic, JScript]
a
A String or a null reference (Nothing in Visual Basic).
b
A String or a null reference (Nothing in Visual Basic).
Parameters [C#, C++]
a
A String or a null reference (Nothing in Visual Basic).
b
A String or a null reference (Nothing in Visual Basic).
Return Value
true if the value of a is the same as the value of b; otherwise, false.
Remarks
This operator is implemented using the Equals method, which means the
comparands are tested for a combination of reference and value equality.
The comparison is case-sensitive.