Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.
This topic has not yet been rated - Rate this topic

String.CompareTo Method (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.

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";
      }
   }
}


Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft. All rights reserved.