String.CompareTo Method

Definition

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.

Overloads

CompareTo(Object)

Compares this instance with a specified Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.

CompareTo(String)

Compares this instance with a specified String object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string.

Remarks

Both overloads of the CompareTo method perform culture-sensitive and case-sensitive comparison. You cannot use this method to perform culture-insensitive or ordinal comparisons. For code clarity, we recommend that you avoid the CompareTo method and call the Compare method instead.

CompareTo(Object)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Compares this instance with a specified Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.

public int CompareTo (object? value);
public int CompareTo (object value);

Parameters

value
Object

An object that evaluates to a String.

Returns

A 32-bit signed integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the value parameter.

Value Condition
Less than zero This instance precedes value.
Zero This instance has the same position in the sort order as value.
Greater than zero This instance follows value.

-or-

value is null.

Implements

Exceptions

value is not a String.

Examples

The following example uses the CompareTo method with an Object. Because it attempts to compare a String instance to a TestClass object, the method throws an ArgumentException.

using System;

public class TestClass
{}

public class Example
{
   public static void Main()
   {
      var test = new TestClass();
      Object[] objectsToCompare = { test, test.ToString(), 123,
                                    123.ToString(), "some text",
                                    "Some Text" };
      string s = "some text";
      foreach (var objectToCompare in objectsToCompare) {
         try {
            int i = s.CompareTo(objectToCompare);
            Console.WriteLine("Comparing '{0}' with '{1}': {2}",
                              s, objectToCompare, i);
         }
         catch (ArgumentException) {
            Console.WriteLine("Bad argument: {0} (type {1})",
                              objectToCompare,
                              objectToCompare.GetType().Name);
         }
      }
   }
}
// The example displays the following output:
//    Bad argument: TestClass (type TestClass)
//    Comparing 'some text' with 'TestClass': -1
//    Bad argument: 123 (type Int32)
//    Comparing 'some text' with '123': 1
//    Comparing 'some text' with 'some text': 0
//    Comparing 'some text' with 'Some Text': -1

Remarks

value must be a String object.

Caution

The CompareTo method was designed primarily for use in sorting or alphabetizing operations. It should not be used when the primary purpose of the method call is to determine whether two strings are equivalent. To determine whether two strings are equivalent, call the Equals method.

This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

For more information about the behavior of this method, see the Remarks section of the String.Compare(String, String) method.

Notes to Callers

Character sets include ignorable characters. The CompareTo(Object) method does not consider such characters when it performs a culture-sensitive comparison. For example, if the following code is run on the .NET Framework 4 or later, a comparison of "animal" with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent.

using System;

public class Example
{
   public static void Main()
   {
      string s1 = "ani\u00ADmal";
      object o1 = "animal";
      
      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, o1, s1.CompareTo(o1));
   }
}
// The example displays the following output:
//       Comparison of 'ani-mal' and 'animal': 0

To recognize ignorable characters in a string comparison, call the CompareOrdinal(String, String) method.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

CompareTo(String)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Compares this instance with a specified String object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string.

public int CompareTo (string strB);
public int CompareTo (string? strB);

Parameters

strB
String

The string to compare with this instance.

Returns

A 32-bit signed integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the strB parameter.

Value Condition
Less than zero This instance precedes strB.
Zero This instance has the same position in the sort order as strB.
Greater than zero This instance follows strB.

-or-

strB is null.

Implements

Examples

The following example uses the CompareTo method to compare the current string instance with another string.

using System;

public class Example
{
   public static void Main()
   {
      string strFirst = "Goodbye";
      string strSecond = "Hello";
      string strThird = "a small string";
      string strFourth = "goodbye";

      // Compare a string to itself.
      Console.WriteLine(CompareStrings(strFirst, strFirst));

      Console.WriteLine(CompareStrings(strFirst, strSecond));
      Console.WriteLine(CompareStrings(strFirst, strThird));

      // Compare a string to another string that varies only by case.
      Console.WriteLine(CompareStrings(strFirst, strFourth));
      Console.WriteLine(CompareStrings(strFourth, strFirst));
   }

   private static string CompareStrings( string str1, string str2 )
   {
      // Compare the values, using the CompareTo method on the first string.
      int cmpVal = str1.CompareTo(str2);

       if (cmpVal == 0) // The strings are the same.
         return "The strings occur in the same position in the sort order.";
      else if (cmpVal < 0)
         return "The first string precedes the second in the sort order.";
      else
         return "The first string follows the second in the sort order.";
    }
}
// The example displays the following output:
//       The strings occur in the same position in the sort order.
//       The first string precedes the second in the sort order.
//       The first string follows the second in the sort order.
//       The first string follows the second in the sort order.
//       The first string precedes the second in the sort order.

The following example demonstrates generic and non-generic versions of the CompareTo method for several value and reference types.

// This example demonstrates the generic and non-generic versions of the
// CompareTo method for several base types.
// The non-generic version takes a parameter of type Object, while the generic
// version takes a type-specific parameter, such as Boolean, Int32, or Double.

using System;

class Sample
{
    public static void Main()
    {
    string    nl = Environment.NewLine;
    string    msg = "{0}The following is the result of using the generic and non-generic{0}" +
                    "versions of the CompareTo method for several base types:{0}";

    DateTime  now = DateTime.Now;
// Time span = 11 days, 22 hours, 33 minutes, 44 seconds
    TimeSpan  tsX = new TimeSpan(11, 22, 33, 44);
// Version = 1.2.333.4
    Version   versX = new Version("1.2.333.4");
// Guid = CA761232-ED42-11CE-BACD-00AA0057B223
    Guid      guidX = new Guid("{CA761232-ED42-11CE-BACD-00AA0057B223}");

    Boolean  a1 = true,  a2 = true;
    Byte     b1 = 1,     b2 = 1;
    Int16    c1 = -2,    c2 = 2;
    Int32    d1 = 3,     d2 = 3;
    Int64    e1 = 4,     e2 = -4;
    Decimal  f1 = -5.5m, f2 = 5.5m;
    Single   g1 = 6.6f,  g2 = 6.6f;
    Double   h1 = 7.7d,  h2 = -7.7d;
    Char     i1 = 'A',   i2 = 'A';
    String   j1 = "abc", j2 = "abc";
    DateTime k1 = now,   k2 = now;
    TimeSpan l1 = tsX,   l2 = tsX;
    Version  m1 = versX, m2 = new Version("2.0");
    Guid     n1 = guidX, n2 = guidX;

// The following types are not CLS-compliant.
    SByte    w1 = 8,     w2 = 8;
    UInt16   x1 = 9,     x2 = 9;
    UInt32   y1 = 10,    y2 = 10;
    UInt64   z1 = 11,    z2 = 11;
//
    Console.WriteLine(msg, nl);
    try
        {
// The second and third Show method call parameters are automatically boxed because
// the second and third Show method declaration arguments expect type Object.

        Show("Boolean:  ", a1, a2, a1.CompareTo(a2), a1.CompareTo((Object)a2));
        Show("Byte:     ", b1, b2, b1.CompareTo(b2), b1.CompareTo((Object)b2));
        Show("Int16:    ", c1, c2, c1.CompareTo(c2), c1.CompareTo((Object)c2));
        Show("Int32:    ", d1, d2, d1.CompareTo(d2), d1.CompareTo((Object)d2));
        Show("Int64:    ", e1, e2, e1.CompareTo(e2), e1.CompareTo((Object)e2));
        Show("Decimal:  ", f1, f2, f1.CompareTo(f2), f1.CompareTo((Object)f2));
        Show("Single:   ", g1, g2, g1.CompareTo(g2), g1.CompareTo((Object)g2));
        Show("Double:   ", h1, h2, h1.CompareTo(h2), h1.CompareTo((Object)h2));
        Show("Char:     ", i1, i2, i1.CompareTo(i2), i1.CompareTo((Object)i2));
        Show("String:   ", j1, j2, j1.CompareTo(j2), j1.CompareTo((Object)j2));
        Show("DateTime: ", k1, k2, k1.CompareTo(k2), k1.CompareTo((Object)k2));
        Show("TimeSpan: ", l1, l2, l1.CompareTo(l2), l1.CompareTo((Object)l2));
        Show("Version:  ", m1, m2, m1.CompareTo(m2), m1.CompareTo((Object)m2));
        Show("Guid:     ", n1, n2, n1.CompareTo(n2), n1.CompareTo((Object)n2));
//
        Console.WriteLine("{0}The following types are not CLS-compliant:", nl);
        Show("SByte:    ", w1, w2, w1.CompareTo(w2), w1.CompareTo((Object)w2));
        Show("UInt16:   ", x1, x2, x1.CompareTo(x2), x1.CompareTo((Object)x2));
        Show("UInt32:   ", y1, y2, y1.CompareTo(y2), y1.CompareTo((Object)y2));
        Show("UInt64:   ", z1, z2, z1.CompareTo(z2), z1.CompareTo((Object)z2));
        }
    catch (Exception e)
        {
        Console.WriteLine(e);
        }
    }

    public static void Show(string caption, Object var1, Object var2,
                            int resultGeneric, int resultNonGeneric)
    {
    string relation;

    Console.Write(caption);
    if (resultGeneric == resultNonGeneric)
        {
        if      (resultGeneric < 0) relation = "less than";
        else if (resultGeneric > 0) relation = "greater than";
        else                        relation = "equal to";
        Console.WriteLine("{0} is {1} {2}", var1, relation, var2);
        }

// The following condition will never occur because the generic and non-generic
// CompareTo methods are equivalent.

    else
        {
        Console.WriteLine("Generic CompareTo = {0}; non-generic CompareTo = {1}",
                           resultGeneric, resultNonGeneric);
        }
   }
}
/*
This example produces the following results:

The following is the result of using the generic and non-generic versions of the
CompareTo method for several base types:

Boolean:  True is equal to True
Byte:     1 is equal to 1
Int16:    -2 is less than 2
Int32:    3 is equal to 3
Int64:    4 is greater than -4
Decimal:  -5.5 is less than 5.5
Single:   6.6 is equal to 6.6
Double:   7.7 is greater than -7.7
Char:     A is equal to A
String:   abc is equal to abc
DateTime: 12/1/2003 5:37:46 PM is equal to 12/1/2003 5:37:46 PM
TimeSpan: 11.22:33:44 is equal to 11.22:33:44
Version:  1.2.333.4 is less than 2.0
Guid:     ca761232-ed42-11ce-bacd-00aa0057b223 is equal to ca761232-ed42-11ce-bacd-00
aa0057b223

The following types are not CLS-compliant:
SByte:    8 is equal to 8
UInt16:   9 is equal to 9
UInt32:   10 is equal to 10
UInt64:   11 is equal to 11
*/

Remarks

This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

Caution

The CompareTo method was designed primarily for use in sorting or alphabetizing operations. It should not be used when the primary purpose of the method call is to determine whether two strings are equivalent. To determine whether two strings are equivalent, call the Equals method.

For more information about the behavior of this method, see the Remarks section of the Compare(String, String) method.

This method implements the System.IComparable<T> interface and performs slightly better than the String.CompareTo(Object) method, because it does not have to determine whether the strB argument is a mutable value type that must be boxed, and it does not have to cast its parameter from an Object to a String.

Notes to Callers

Character sets include ignorable characters. The CompareTo(String) method does not consider such characters when it performs a culture-sensitive comparison. For example, if the following code is run on the .NET Framework 4 or later, a comparison of "animal" with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent.

using System;

public class Example
{
   public static void Main()
   {
      string s1 = "ani\u00ADmal";
      string s2 = "animal";
      
      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, s2, s1.CompareTo(s2));
   }
}
// The example displays the following output:
//       Comparison of 'ani-mal' and 'animal': 0

To recognize ignorable characters in a string comparison, call the CompareOrdinal(String, String) method.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0