String.CompareTo Method (Object)
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
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.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- value
- Type: System.Object
An object that evaluates to a String.
Return Value
Type: System.Int32A 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)| Exception | Condition |
|---|---|
| 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: |
|---|
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"; } } }
Caution: