Char.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 to a specified object and returns an integer that indicates whether this instance precedes, follows, or has the same position in the sort order as the specified object.

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

Syntax

Public Function CompareTo ( _
    value As Object _
) As Integer
public int CompareTo(
    Object value
)

Parameters

  • value
    Type: System..::.Object
    An object to compare this instance to, or nullNothingnullptra null reference (Nothing in Visual Basic).

Return Value

Type: System..::.Int32
A signed number that indicates the position of this instance in the sort order in relation to the value parameter.

Return Value

Description

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 is follows value.

-or-

value is nullNothingnullptra null reference (Nothing in Visual Basic).

Implements

IComparable..::.CompareTo(Object)

Exceptions

Exception Condition
ArgumentException

value is not a Char object.

Remarks

The CompareTo method implements the IComparable interface.

The value parameter must be nullNothingnullptra null reference (Nothing in Visual Basic) or an instance of Char; otherwise, an exception is thrown.

The comparison performed by this method is based on the encoded values of this instance and value, not necessarily their lexicographical characteristics. Any instance of Char, regardless of its value, is considered greater than nullNothingnullptra null reference (Nothing in Visual Basic).

Examples

The following example demonstrates CompareTo.


Module Example

   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      Dim chA As Char
      chA = "A"c
      Dim chB As Char
      chB = "B"c

      outputBlock.Text &= chA.CompareTo("A"c)   ' Output: "0" (meaning they're equal & vbCrLf
      outputBlock.Text &= "b"c.CompareTo(chB)   ' Output: "32" (meaning 'b' is 32 greater than 'B' & vbCrLf
      outputBlock.Text &= chA.CompareTo(chB)    ' Output: "-1" (meaning 'A' is less than 'B' by 1 & vbCrLf

   End Sub

End Module
using System;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      char chA = 'A';
      char chB = 'B';

      outputBlock.Text += chA.CompareTo('A') + "\n";    // Output: "0" (meaning they're equal)
      outputBlock.Text += 'b'.CompareTo(chB) + "\n";    // Output: "32" (meaning 'b' is greater than 'B' by 32)
      outputBlock.Text += chA.CompareTo(chB) + "\n";    // Output: "-1" (meaning 'A' is less than 'B' by 1)
   }
}

Version Information

Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Platforms

Windows Phone

See Also

Reference

Char Structure

CompareTo Overload

System Namespace

IComparable

Char..::.Equals