String.CompareTo Method (Object)

July 28, 2014

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.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public int CompareTo(
	Object value
)

Parameters

value
Type: System.Object
An object that evaluates to a String.

Return Value

Type: System.Int32
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

IComparable.CompareTo(Object)

ExceptionCondition
ArgumentException

value is not a String.

value must be a String object.

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 noteCaution:

The CompareTo(Object) method is 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 (that is, when the purpose of the method call is to test for a return value of zero). 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 method.

The following code example demonstrates how you can use the CompareTo method with an Object.


using System;

public class MyClass { }
public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      MyClass my = new MyClass();
      string s = "sometext";
      try
      {
         int i = s.CompareTo(my);
      }
      catch (Exception e)
      {
         outputBlock.Text += String.Format("Error: {0}", e.ToString()) + "\n";
      }
   }
}


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2014 Microsoft