Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed?
string testString = "Test";
string anotherString = "Another";
if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)
Here are the rules for how these functions work:
stringValue.CompareTo(otherStringValue)
null
comes before a stringCultureInfo.CurrentCulture.CompareInfo.Compare
, which means it will use a culture-dependent comparison. This might mean thatß
will compare equal toSS
in Germany, or similarstringValue.Equals(otherStringValue)
null
is not considered equal to anythingStringComparison
option, it will use what looks like a direct ordinal equality check, i.e.ß
is not the same asSS
, in any language or culturestringValue == otherStringValue
stringValue.Equals()
.==
operator calls the staticEquals(string a, string b)
method (which in turn goes to an internalEqualsHelper
to do the comparison..Equals()
on anull
string getsnull
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.From MSDN:
They suggest using
.Equals
instead of.CompareTo
when looking solely for equality. I am not sure if there is a difference between.Equals
and==
for thestring
class. I will sometimes use.Equals
orObject.ReferenceEquals
instead of==
for my own classes in case someone comes along at a later time and redefines the==
operator for that class.As Ed said, CompareTo is used for sorting.
There is a difference, however, between .Equals and ==.
== resolves to essentially the following code:
The simple reason is the following will throw an exception:
And the following will not:
One BIG difference to note is .Equals() will throw an exception if first string is null, Whereas == will not.
If you are ever curious about differences in BCL methods, Reflector is your friend :-)
I follow these guidelines:
Exact match: EDIT: I previously always used == operator on the principle that inside Equals(string, string) the object == operator is used to compare the object references but it seems strA.Equals(strB) is still 1-11% faster overall than string.Equals(strA, strB), strA == strB, and string.CompareOrdinal(strA, strB). I loop tested with a StopWatch on both interned/non-interned string values, with same/different string lengths, and varying sizes (1B to 5MB).
Human-readable match (Western cultures, case-insensitive):
Human-readable match (All other cultures, insensitive case/accent/kana/etc defined by CultureInfo):
Human-readable match with custom rules (All other cultures):
Good explanation and practices about string comparison issues may be found in the article New Recommendations for Using Strings in Microsoft .NET 2.0 and also in Best Practices for Using Strings in the .NET Framework.
Each of mentioned method (and other) has particular purpose. The key difference between them is what sort of StringComparison Enumeration they are using by default. There are several options:
Each of above comparison type targets different use case:
Note, that StringComparison Enumeration as well as overloads for string comparison methods, exists since .NET 2.0.
String.CompareTo Method (String)
Is in fact type safe implementation of IComparable.CompareTo Method. Default interpretation: CurrentCulture.
Usage:
Thus
String.Compare Method
A static member of String Class which has many overloads. Default interpretation: CurrentCulture.
String.Equals Method
Overriden from Object class and overloaded for type safety. Default interpretation: Ordinal. Notice that:
StringComparer class
There is also another way to deal with string comparisons especially aims to sorting: