Here are the rules for how these functions work:
stringValue.CompareTo(otherStringValue)
null
comes before a string
- it uses
CultureInfo.CurrentCulture.CompareInfo.Compare
, which means it will use a culture-dependent comparison. This might mean that ?
will compare equal to SS
in Germany, or similar
stringValue.Equals(otherStringValue)
null
is not considered equal to anything
- unless you specify a
StringComparison
option, it will use what looks like a direct ordinal equality check, i.e. ?
is not the same as SS
, in any language or culture
stringValue == otherStringValue
- Is not the same as
stringValue.Equals()
.
- The
==
operator calls the static Equals(string a, string b)
method (which in turn goes to an internal EqualsHelper
to do the comparison.
- Calling
.Equals()
on a null
string gets null
reference exception, while on ==
does not.
Object.ReferenceEquals(stringValue, otherStringValue)
Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.
Note that with the options above that use method calls, there are overloads with more options to specify how to compare.
My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use .CompareTo
or .Equals
, depending on the choice.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…