Possible Duplicate:
Differences in string compare methods in C#
In .NET there are many string comparison methods, I just want to confirm which one is the best to use considering performance.
string.Equals() string.Compare() string.CompareTo() string.CompareOrdinal() string.ReferenceEquals() if (str1 == str2)
string= compares two strings and is true if they are the same (corresponding characters are identical) but is false if they are not. The function equal calls string= if applied to two strings. The keyword arguments :start1 and :start2 are the places in the strings to start the comparison.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
Ripped from msdn
string.Equals
Determines whether this instance and a specified object, which must also be a String object, have the same value.
string.Compare Compares two specified String objects and returns an integer that indicates their relative position in the sort order.
string.CompareTo Compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified object or String.
string.CompareOrdinal Compares two specified String objects by evaluating the numeric values of the corresponding Char objects in each string.
String equality operators The predefined string equality operators are:
bool operator ==(string x, string y); bool operator !=(string x, string y); Two string values are considered equal when one of the following is true:
Both values are null. Both values are non-null references to string instances that have identical lengths and identical characters in each character position. The string equality operators compare string values rather than string references. When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different. As described in Section 7.9.6, the reference type equality operators can be used to compare string references instead of string values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With