I was reading about best practices for comparing strings and saw these two points:
Unfortunately no explanation is provided as to why it's not recommended.
Can someone explain why it's bad to use CompareTo()
to check for equality?
If you look at the documentation for CompareTo
it provides an example of a comparison that returns 0
for two strings that should sort equally but are not equal. If we modify the sample slightly:
using System;
public class Program
{
public static void Main()
{
string s1 = "ani\u00ADmal";
string o1 = "animal";
Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
s1, o1, s1.CompareTo(o1));
Console.WriteLine("Are equal? '{0}'", s1.Equals(o1));
}
}
Result:
Comparison of 'animal' and 'animal': 0
Are equal? 'False'
Of course, the other reason to avoid them is that using Equals
more clearly encodes your intent if you're trying to test for equality.