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)nullcomes before a stringCultureInfo.CurrentCulture.CompareInfo.Compare, which means it will use a culture-dependent comparison. This might mean thatßwill compare equal toSSin Germany, or similarstringValue.Equals(otherStringValue)nullis not considered equal to anythingStringComparisonoption, it will use what looks like a direct ordinal equality check, i.e.ßis not the same asSS, in any language or culturestringValue == otherStringValuestringValue.Equals().==operator calls the staticEquals(string a, string b)method (which in turn goes to an internalEqualsHelperto do the comparison..Equals()on anullstring getsnullreference 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
.CompareToor.Equals, depending on the choice.