Search code examples
.netstringstring-comparison

Why is CompareTo() not recommended for checking equality?


I was reading about best practices for comparing strings and saw these two points:

  • Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.
  • Don't use an overload of the String.Compare or CompareTo method and test for a return value of zero to determine whether two strings are equal.

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?


Solution

  • 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 'ani­mal' 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.