Char.CompareTo() Method in C#


The Char.CompareTo() method in C# is used to compare this instance to a specified object or value type, and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified object or value type.

Syntax

Following is the syntax −

public int CompareTo (char val);
public int CompareTo (object val);

Above, Val for the 1st syntax is a char object to compare, whereas for the 2nd syntax it is an object to compare this instance to or null.

The return value is zero if the current instance has the same position in the sort order as Val. It’s less than zero if the current instance is less than Val. The return value is greater than zero if the current instance follows Val.

Example

Let us now see an example to implement the Char.CompareTo() method −

using System;
public class Demo {
   public static void Main(){
      char val = 'A';
      Console.WriteLine("Return Value = "+'A'.CompareTo(val));
   }
}

Output

This will produce the following output −

Return Value = 0

Example

Let us see another example −

using System;
public class Demo {
   public static void Main(){
      char val = 'B';
      Console.WriteLine("Return Value = "+'D'.CompareTo(val));
   }
}

Output

This will produce the following output −

Return Value = 2
raja
Published on 08-Nov-2019 11:04:30
Advertisements