C# String CompareTo(Object)
Description
String 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.
Syntax
String.CompareTo(Object)
has the following syntax.
public int CompareTo(
Object value
)
Parameters
String.CompareTo(Object)
has the following parameters.
value
- An object that evaluates to a String.
Returns
String.CompareTo(Object)
method 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.
Example
A comparison of "animal" with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent, as the following example shows.
using System;//w ww . j a v a 2 s . c om
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 code above generates the following result.
Example 2
The following example demonstrates how you can use the CompareTo method with an Object. using System;
using System;// ww w . j ava 2s . c o m
public class MyClass {}
public class Example
{
public static void Main()
{
MyClass my = new MyClass();
string s = "sometext";
try
{
int i = s.CompareTo(my);
}
catch (Exception e)
{
Console.WriteLine("Error: {0}",e.ToString());
}
}
}
The code above generates the following result.